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.9

Permissions in 0.2.9

  • Control chats chats.controlHighCreates chats, sends prompts and cancels runs.Send prompts, answer agent questions, and create, change, fork, revert, stop and group chats
  • Run other plugins' commands commands.runHighRuns commands of other plugins.Run the sidebar's New chat command from the title bar, and its Close Chat and Reopen Closed Chat for Cmd+W and Cmd+Shift+T on a chat's only tab
  • Read chats chats.readMediumReads your transcripts and chat lists.Show workspaces, tasks, chats and transcripts, and follow them as agents work
  • Read files fs.readMediumReads files in the listed places.Suggest workspace files for @ mentionsPlaces: the open workspace
  • Show panels ui.slotsAlways grantedShows views in the listed parts of the window.Draw the chat grid, the title bar, and the Session panel with its rail buttonSlots: centertitlerailright

Files

find.ts11.8 KB
// Find in Chat (Cmd+F, Ctrl+F off the Mac): a bar over the transcript that searches the chat's messages, the user's
// and the agent's replies, for what is typed. Every match is marked in the text and the reader steps through them;
// the match the reader is on is drawn stronger and brought into view.
//
// The plugin counts the matches of each message in the text its markdown draws, the way the kernel counts them
// (`crates/kernel/src/markdown/find.rs`): ignoring case, one character at a time, never overlapping, in reading
// order. The text drawn is worked out from the Markdown here, near enough for a search: a link's address, emphasis
// marks, a heading's hashes and a list's markers are not drawn, so they are not searched.
import * as Effect from "effect/Effect";
import type { TranscriptItem } from "divergence";
import type { Controller } from "./controller.ts";
import { markedMessage } from "./message-text.ts";
import type { Transcript } from "./state.ts";
import { entriesOf, withoutSpawnRows } from "./subagents.ts";
import { revision } from "./transcript.ts";
import { entryId, moveWindow, windows } from "./window.ts";

/** One match: the message it is in and its number there, from 0 in reading order. */
export type Hit = { id: string; index: number };

/** The bar of one chat while it is open. */
export type Find = {
  query: string;
  /** The match the reader is on. It is kept by message, so older messages read in do not move it. */
  current: Hit | null;
  /** How many times the reader moved to a match: each move brings the match into view. */
  moves: number;
};

/** What a message's markdown is told to mark (`MarkdownFind`). */
export type Marking = { query: string; current?: number; reveal?: number };

/** `text` lowercase one character at a time, as the kernel compares it. */
export function lowercase(text: string): string {
  let out = "";
  for (const ch of text) out += ch.toLowerCase();
  return out;
}

/** How many times `query` (lowercase) occurs in `text` (lowercase), without overlaps. */
export function countIn(text: string, query: string): number {
  if (!query) return 0;
  let count = 0;
  for (let at = text.indexOf(query); at >= 0; at = text.indexOf(query, at + query.length)) count++;
  return count;
}

const FENCE = /^ {0,3}(`{3,}|~{3,})/;
const DELIMITER_ROW = /^ {0,3}\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
const RULE = /^ {0,3}([-*_])(\s*\1){2,}\s*$/;
const BLOCK_START = /^ {0,3}(#{1,6}\s|>|[-*+]\s|\d+[.)]\s|\|)/;

/**
 * The text a message's markdown draws, near enough to count matches in: the code of a fence as written, and of every
 * other line its words without the marks around them. Lines of one paragraph join with a space where its breaks are
 * soft (an agent's reply) and stay lines where they are hard (a message the user typed, `keepLineBreaks`); a table's
 * cells are lines of their own, as the kernel draws each cell apart.
 */
export function drawnText(markdown: string, breaks: "soft" | "hard"): string {
  const out: string[] = [];
  let fence: string | null = null;
  let joins = false;
  for (const line of markdown.split("\n")) {
    const marker = FENCE.exec(line)?.[1];
    if (fence !== null) {
      if (marker && marker[0] === fence[0] && marker.length >= fence.length && !line.trim().slice(marker.length)) fence = null;
      else out.push(line);
      continue;
    }
    if (marker) {
      fence = marker;
      joins = false;
      continue;
    }
    if (!line.trim() || DELIMITER_ROW.test(line) || RULE.test(line)) {
      joins = false;
      continue;
    }
    if (/^ {0,3}\|/.test(line)) {
      out.push(...line.trim().replace(/^\||\|$/g, "").split(/(?<!\\)\|/).map((cell) => inlineText(cell.trim())));
      joins = false;
      continue;
    }
    const starts = BLOCK_START.test(line);
    const words = inlineText(
      line
        .replace(/^ {0,3}(>\s?)+/, "")
        .replace(/^\s*([-*+]|\d+[.)])\s+(\[[ xX]\]\s+)?/, "")
        .replace(/^#{1,6}\s+/, "")
        .trim(),
    );
    if (joins && !starts && breaks === "soft") out[out.length - 1] += ` ${words}`;
    else out.push(words);
    joins = true;
  }
  return out.join("\n");
}

/**
 * A line's words as drawn: code spans as written, a link whose label is one (a sent message's tags) as its label, and
 * around them no link addresses, emphasis marks or escapes.
 */
function inlineText(line: string): string {
  let out = "",
    at = 0;
  for (const span of line.matchAll(/\[(`+)([\s\S]*?[^`])\1\]\((?:<[^>]*>|[^)\s]*)(?:\s+"[^"]*")?\)|(`+)([\s\S]*?[^`])\3(?!`)/g)) {
    out += prose(line.slice(at, span.index)) + (span[2] ?? span[4])!;
    at = span.index + span[0].length;
  }
  return out + prose(line.slice(at));
}

function prose(text: string): string {
  return text
    .replace(/!?\[([^\]]*)\]\((?:<[^>]*>|[^)\s]*)(?:\s+"[^"]*")?\)/g, "$1")
    .replace(/<((?:https?|mailto):[^>\s]+)>/g, "$1")
    .replace(/~~|\*+(?=\S)|(?<=\S)\*+/g, "")
    .replace(/(?<![\p{L}\p{N}])_+(?=\S)|(?<=\S)_+(?![\p{L}\p{N}])/gu, "")
    .replace(/\\([!-/:-@[-`{-~])/g, "$1");
}

/** A message's text as its markdown draws it, or null for a row that is no message. */
export function messageText(c: Pick<Controller, "plainText">, item: TranscriptItem): string | null {
  if (item.role === "assistant") return item.text.trim() ? drawnText(item.text, "soft") : null;
  if (item.role !== "user") return null;
  const text = c.plainText(item.blocks);
  if (!text) return null;
  // The bubble draws a file it names by its name alone; the commands and skills it marks only gain backticks.
  return drawnText(item.from != null ? text : markedMessage(text, item.blocks, { mentions: undefined, skills: [], commands: [] }), "hard");
}

// Each message's text as searched (lowercase) and its matches of the last query, worked out again only when the
// message or the query changed, so a chat that streams with the bar open counts only the reply that grows.
const searched = new WeakMap<TranscriptItem, { revision: number; text: string | null; query: string; count: number }>();

function matchesIn(c: Pick<Controller, "plainText">, item: TranscriptItem, query: string): number {
  let known = searched.get(item);
  if (!known || known.revision !== revision(item)) {
    const text = messageText(c, item);
    known = { revision: revision(item), text: text === null ? null : lowercase(text), query: "", count: 0 };
    searched.set(item, known);
  }
  if (known.text !== null && known.query !== query) {
    known.query = query;
    known.count = countIn(known.text, query);
  }
  return known.text === null ? 0 : known.count;
}

/** Every match of `query` in the chat's messages, in reading order. */
export function hitsIn(c: Pick<Controller, "plainText">, items: readonly TranscriptItem[], query: string): Hit[] {
  const wanted = lowercase(query);
  const hits: Hit[] = [];
  if (!wanted) return hits;
  for (const item of items) {
    const count = matchesIn(c, item, wanted);
    for (let index = 0; index < count; index++) hits.push({ id: item.id, index });
  }
  return hits;
}

/** Where `hit` is among `hits`, or -1. */
export function positionOf(hits: readonly Hit[], hit: Hit | null): number {
  return hit ? hits.findIndex((other) => other.id === hit.id && other.index === hit.index) : -1;
}

/**
 * The match a step `by` one from `current` lands on, going round at either end. A current match that went (its
 * message changed) steps from the first match after where it was, or the last for a step back.
 */
export function stepped(hits: readonly Hit[], current: Hit | null, by: 1 | -1, order: (id: string) => number): Hit | null {
  if (!hits.length) return null;
  const at = positionOf(hits, current);
  if (at >= 0) return hits[(at + by + hits.length) % hits.length]!;
  if (!current) return by > 0 ? hits[0]! : hits[hits.length - 1]!;
  const place = order(current.id);
  const after = hits.findIndex((hit) => order(hit.id) > place || (hit.id === current.id && hit.index > current.index));
  if (by > 0) return hits[after >= 0 ? after : 0]!;
  const before = (after >= 0 ? after : hits.length) - 1;
  return hits[before >= 0 ? before : hits.length - 1]!;
}

/** The chat's matches for its bar's query. */
export function chatHits(c: Pick<Controller, "plainText">, t: Transcript): Hit[] {
  return hitsIn(c, t.items, t.find?.query ?? "");
}

/** What each message with a match marks, by message id: the query, and in the reader's message their match. */
export function markings(c: Pick<Controller, "plainText">, t: Transcript): Map<string, Marking> {
  const marks = new Map<string, Marking>();
  const find = t.find;
  if (!find?.query) return marks;
  for (const hit of chatHits(c, t)) if (!marks.has(hit.id)) marks.set(hit.id, { query: find.query });
  const current = find.current && marks.get(find.current.id);
  if (current && find.current) marks.set(find.current.id, { ...current, current: find.current.index, reveal: find.moves });
  return marks;
}

// What each message of a transcript marks as it is drawn now, set by the transcript before its rows draw.
const drawnMarkings = new WeakMap<Transcript, Map<string, Marking>>();

/** Works out what the transcript's messages mark for the rows about to be drawn. */
export function markTranscript(c: Pick<Controller, "plainText">, t: Transcript) {
  drawnMarkings.set(t, markings(c, t));
}

/** What the message `id` marks, if it has a match. */
export function markingOf(t: Transcript, id: string): Marking | undefined {
  return drawnMarkings.get(t)?.get(id);
}

/** A message's marking as a row's input: its row draws again only when this changes. */
export function markingKey(marking: Marking | undefined): string | null {
  return marking ? `${marking.query}\u0000${marking.current ?? ""}\u0000${marking.reveal ?? ""}` : null;
}

/** Opens the chat's bar, or takes the keyboard back to an open one, and reads the rest of the chat's history so
 * every message is searched; the bar searches what is read already meanwhile. */
export const openFind = Effect.fn("Chat.openFind")(function* (c: Controller, chatId: string) {
  const t = c.transcript(chatId);
  t.find ??= { query: "", current: null, moves: 0 };
  c.refresh(chatId);
  yield* c.views.focus(`find-${chatId}`);
  // A page another read has in flight leaves the start where it was: the bar searches what that read brings.
  for (let start = -1; t.find && t.start > 0 && t.start !== start; ) {
    start = t.start;
    yield* c.loadOlder(chatId, start);
  }
});

/** Closes the chat's bar: no message is marked any more. */
export function closeFind(c: Controller, chatId: string) {
  const t = c.transcript(chatId);
  if (!t.find) return;
  t.find = undefined;
  c.refresh(chatId);
}

/** The bar's text changed: the reader goes to the newest match, the one nearest the end where a chat is read. */
export function search(c: Controller, chatId: string, query: string) {
  const t = c.transcript(chatId);
  if (!t.find) return;
  t.find.query = query;
  const hits = chatHits(c, t);
  goTo(c, t, chatId, hits[hits.length - 1] ?? null);
}

/** Steps to the older match (-1, Enter) or the newer one (1, Shift+Enter). */
export function step(c: Controller, chatId: string, by: 1 | -1) {
  const t = c.transcript(chatId);
  if (!t.find) return;
  const order = new Map(t.items.map((item, index) => [item.id, index]));
  goTo(c, t, chatId, stepped(chatHits(c, t), t.find.current, by, (id) => order.get(id) ?? -1));
}

function goTo(c: Controller, t: Transcript, chatId: string, hit: Hit | null) {
  const find = t.find!;
  find.current = hit;
  find.moves++;
  if (hit) {
    // A prompt cut to its first lines opens, so the match in it shows.
    if (t.clamped.has(hit.id)) t.expanded.add(hit.id);
    // A long transcript draws the rows around the match.
    if (windows()) {
      const entries = entriesOf(withoutSpawnRows(t.items), c.api.settings.get("groupTools") !== false);
      const at = entries.findIndex((entry) => entry.kind === "item" && entry.item.id === hit.id);
      if (at >= 0) moveWindow(t, entries, at, entryId);
    }
  }
  c.refresh(chatId);
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.9latestNov 21, 2026>=5 <6349 KB5 permissionsListed
0.2.8Nov 16, 2026>=5 <6348.6 KB5 permissionsListed
0.2.7Nov 11, 2026>=5 <6314.3 KB5 permissionsListed
0.2.6Nov 9, 2026>=5 <6306.2 KB5 permissionsListed
0.2.5Oct 27, 2026>=2 <4178.6 KB5 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.