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

data.ts26.6 KB
// Request failures recover at the same notification/logging boundaries as the JavaScript baseline.
// Load persisted chat state and refresh agent history without adding work to streaming deltas.
// Storage schemas validate the untyped values before they enter the per-chat maps.
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as z from "zod";
import { parse } from "divergence/effect";
import type { Chat, TranscriptItem } from "divergence";
import type { Controller, ChatError } from "./controller.ts";
import { draftTitle } from "./title.ts";
import { allTasks, entriesOf, isLive, taskItems, withoutSpawnRows } from "./subagents.ts";
import { CYCLE_LIMIT } from "./switcher.ts";
import { contentBlocks, legacyId } from "./input-schema.ts";
import { blocksFor } from "./composition.ts";
import { noteSession, readRun } from "./transcript.ts";
import { registeredPane } from "./state.ts";
import type { Transcript } from "./state.ts";
import { carryFold } from "./grouping.ts";

const textMap = z.record(z.string(), z.string());
// Restored queues need opaque image ids; historical entries may omit attachment metadata.
const attachment = z.object({ id: z.string(), name: z.string().optional() }).passthrough();
const prompt = z.union([
  z.string().transform((text) => ({ text, attachments: [], blocks: undefined, id: undefined })),
  z.object({
    text: z.string(),
    attachments: z.array(attachment),
    blocks: contentBlocks.optional(),
    id: z.string().optional(),
  }),
]);
const queues = z.object({
  prompts: z.record(z.string(), z.array(prompt)).optional(),
  // `text` is from before a queued draft kept its prompt in the composer.
  chats: z.array(z.object({ chatId: z.string(), text: z.string().optional() })).optional(),
});

// The sidebar follows the queue and the draft titles through the
// divergence/chat service; these snapshot the state for its events. The
// shared writes they replace also re-rendered this plugin's own views
// through app_state, so they refresh the views that show them too: the
// center for the queue, the title (and its switcher) for draft titles.
export const announceQueued = (c: Controller): Effect.Effect<void> =>
  Effect.sync(() => {
    c.emitQueued?.(c.state.chatQueue.map((queued) => queued.chatId));
    c.center?.update();
    c.titleView?.update();
  });
export const announceDrafts = (c: Controller, chatId: string): Effect.Effect<void> =>
  Effect.sync(() => {
    c.emitDrafts?.({ ...c.state.draftTitles });
    c.presentations?.updateTitle(chatId);
  });
// Marks a chat as starting a run, or no longer, and tells the sidebar.
export function setStarting(c: Controller, chatId: string, starting: boolean) {
  if (c.state.starting.has(chatId) === starting) return;
  if (starting) c.state.starting.add(chatId);
  else c.state.starting.delete(chatId);
  c.emitStarting?.([...c.state.starting]);
}
export const loadRecent = Effect.fn("Chat.loadRecent")(function* (c: Controller) {
  const value = (yield* c.host.call("host/storage.get", { key: "recent" })).value;
  if (Array.isArray(value)) c.state.recent = value.filter((id): id is string => typeof id === "string");
});
export const noteRecent = Effect.fn("Chat.noteRecent")(function* (c: Controller, chatId: string) {
  if (c.state.recent[0] === chatId) return;
  c.state.recent = [chatId, ...c.state.recent.filter((id) => id !== chatId)].slice(0, CYCLE_LIMIT);
  yield* c.host.call("host/storage.set", { key: "recent", value: c.state.recent });
});
export const syncDraftTitle = Effect.fn("Chat.syncDraftTitle")(function* (c: Controller, chatId: string) {
  const chat = c.state.chats[chatId];
  const composer = c.state.composers[chatId];
  const first = c.state.transcripts[chatId]?.items.find((item) => item.role === "user");
  const text = first
    ? c.plainText(first.blocks)
    : (composer?.outgoing?.text ?? composer?.text ?? c.state.restored?.[chatId] ?? "");
  const title = chat?.title === "New Chat" ? draftTitle(text) : null;
  if ((c.state.draftTitles[chatId] ?? null) === title) return;
  if (title) c.state.draftTitles[chatId] = title;
  else delete c.state.draftTitles[chatId];
  yield* announceDrafts(c, chatId);
});
export const syncDraftTitles = Effect.fn("Chat.syncDraftTitles")(function* (c: Controller) {
  const ids = new Set([
    ...Object.keys(c.state.composers),
    ...Object.keys(c.state.restored ?? {}),
    ...c.state.chatQueue.map((q) => q.chatId),
  ]);
  for (const id of ids) yield* syncDraftTitle(c, id);
});
export const saveUnsent = Effect.fn("Chat.saveUnsent")(function* (c: Controller): Effect.fn.Return<void, ChatError> {
  c.state.unsaved = true;
  if (c.state.saving || !c.state.restored) return;
  c.state.saving = true;
  yield* Effect.gen(function* () {
    while (c.state.unsaved) {
      c.state.unsaved = false;
      const value = { ...c.state.restored };
      for (const [id, composer] of Object.entries(c.state.composers)) {
        yield* c.drafts.save(id);
        if (composer.text) value[id] = composer.text;
        else delete value[id];
      }
      const result = yield* c.host.call("host/storage.set", { key: "unsent", value }).pipe(
        Effect.as(true),
        Effect.catch((error) =>
          c.notify.error(`Unsent prompts could not be saved: ${errorMessage(error)}`).pipe(Effect.as(false)),
        ),
      );
      if (!result) {
        c.state.unsaved = true;
        break;
      }
    }
  }).pipe(
    Effect.catch((error) =>
      Effect.gen(function* () {
        c.state.unsaved = true;
        yield* c.notify.error(`Unsent prompts could not be saved: ${errorMessage(error)}`);
      }),
    ),
    Effect.ensuring(
      Effect.sync(() => {
        c.state.saving = false;
      }),
    ),
  );
});
// A new chat's draft title is its first line, so it changes with every
// key, and the title bar and the sidebar take it at once. Their frames
// present in the refresh's late slot (`gpui::present_pacer` in our GPUI),
// so they never stand in front of the next key's.
export const textChanged = Effect.fn("Chat.textChanged")(function* (c: Controller, chatId: string) {
  const composer = c.composer(chatId);
  composer.editVersion = (composer.editVersion ?? 0) + 1;
  yield* syncDraftTitle(c, chatId);
  yield* Effect.forkIn(saveUnsent(c), c.scope, { startImmediately: true });
});
export const restoreUnsent = Effect.fn("Chat.restoreUnsent")(function* (c: Controller) {
  yield* Effect.gen(function* () {
    const stored = yield* parse(
      "unsent prompts",
      textMap,
      (yield* c.host.call("host/storage.get", { key: "unsent" })).value ?? {},
    );
    c.state.restored = {};
    for (const [id, text] of Object.entries(stored)) {
      if ((c.drafts.snapshots[id]?.revision ?? 0) > 0) continue;
      const composer = c.state.composers[id];
      if (!composer) c.state.restored[id] = text;
      else if (!composer.text) composer.text = text;
    }
    yield* syncDraftTitles(c);
    if (c.state.unsaved) yield* Effect.forkIn(saveUnsent(c), c.scope, { startImmediately: true });
    c.view.update();
  }).pipe(Effect.catch((error) => c.notify.error(`Unsent prompts could not be read: ${errorMessage(error)}`)));
});
export const persistQueues = Effect.fn("Chat.persistQueues")(function* (c: Controller) {
  const prompts = Object.fromEntries(
    Object.entries(c.state.composers)
      .filter(([, composer]) => composer.queue.length)
      .map(([id, composer]) => [id, composer.queue]),
  );
  yield* c.host.call("host/storage.set", {
    key: "queues",
    value: { prompts, chats: c.state.chatQueue },
  });
});
export const restoreQueues = Effect.fn("Chat.restoreQueues")(function* (c: Controller) {
  const value = (yield* c.host.call("host/storage.get", { key: "queues" })).value;
  if (!value) return;
  const stored = yield* parse("prompt queues", queues, value);
  c.state.chatQueue = (stored.chats ?? []).map(({ chatId }) => ({ chatId }));
  for (const { chatId, text } of stored.chats ?? []) {
    if (!text) continue;
    yield* c.ensureComposer(chatId);
    const composer = c.composer(chatId);
    if (!composer.text) composer.text = text;
  }
  if (stored.chats?.some((queued) => queued.text)) {
    yield* Effect.forkIn(saveUnsent(c), c.scope, { startImmediately: true });
    yield* persistQueues(c);
  }
  for (const [id, queue] of Object.entries(stored.prompts ?? {})) {
    yield* c.ensureComposer(id);
    // Assign stable keys before deleting any source row. A crash after host
    // enqueue but before saving the migration can only repeat an idempotent key.
    c.composer(id).queue = queue.map((entry, index) => ({ ...entry, id: entry.id ?? legacyId(id, index, entry) }));
  }
  if (Object.keys(stored.prompts ?? {}).length) yield* persistQueues(c);
  for (const id of Object.keys(stored.prompts ?? {})) {
    yield* c.scheduler.load(id);
    if (c.scheduler.available !== true) continue;
    const composer = c.composer(id);
    for (const entry of [...composer.queue])
      yield* Effect.gen(function* () {
        const blocks = entry.blocks ?? (yield* blocksFor(c, id, entry.text, entry.attachments));
        const key = entry.id ?? legacyId(id, 0, entry);
        yield* c.scheduler.enqueue(id, key, blocks, "queue", "legacy_queue");
        composer.queue = composer.queue.filter((input) => input.id !== key);
        yield* persistQueues(c);
      }).pipe(Effect.catch((error) => c.scheduler.report(id, error)));
  }
  yield* announceQueued(c);
  yield* syncDraftTitles(c);
  c.view.update();
  yield* Effect.forkIn(c.pumpChatQueue(), c.scope, { startImmediately: true });
});
export const loadOptions = Effect.fn("Chat.loadOptions")(function* (c: Controller, chatId: string) {
  const composer = c.composer(chatId);
  const agentId = c.state.chats[chatId]?.agentId ?? null;
  const switched = composer.agentId !== agentId;
  if (switched) {
    // Another agent's settings say nothing about this one's: while they
    // load the pickers show this agent's last answer (or none), and if
    // they fail none, never the last agent's model.
    composer.agentId = agentId;
    composer.options = (agentId && c.state.agentOptions[agentId]) || [];
    composer.commands = [];
    composer.skills = [];
  }
  composer.loading = true;
  // Drawn at once: the kernel's spinner shows only if the read outlasts
  // its delay (the host answers saved lists well within it).
  c.view.update();
  yield* c.host.call("host/chats.options", { chatId }).pipe(
    Effect.tap((result) =>
      Effect.sync(() => {
        // The chat moved to another agent meanwhile: these are the last
        // agent's, and the new agent's own read is on its way.
        if (composer.agentId !== agentId) return;
        composer.options = result.options;
        if (agentId) c.state.agentOptions[agentId] = result.options;
      }),
    ),
    Effect.catch((error) => {
      if (composer.agentId !== agentId) return Effect.void;
      // The list shown since the switch was another chat's answer.
      if (switched) composer.options = [];
      return c.notify.warning(`Options unavailable: ${errorMessage(error)}`);
    }),
  );
  if (composer.agentId !== agentId) return;
  // Loading ends with the options. Commands and skills can wait for the
  // agent (a catalog saved before them has none): they apply when they
  // arrive and never hold Send.
  composer.loading = false;
  c.view.update();
  c.updateSession(chatId);
  const apply = <A, E extends Parameters<typeof errorMessage>[0], R>(call: Effect.Effect<A, E, R>, set: (result: A) => void, what?: string) =>
    Effect.forkIn(
      call.pipe(
        Effect.tap((result) =>
          Effect.sync(() => {
            if (composer.agentId !== agentId) return;
            set(result);
            c.view.update();
          }),
        ),
        Effect.catch((error) =>
          composer.agentId === agentId && what ? c.notify.warning(`${what} unavailable: ${errorMessage(error)}`) : Effect.void,
        ),
      ),
      c.scope,
      { startImmediately: true },
    );
  yield* apply(c.host.call("host/chats.commands", { chatId }), (r) => (composer.commands = r.commands), "Commands");
  yield* apply(c.host.call("host/chats.skills", { chatId }), (r) => (composer.skills = r.skills));
});
// Every chat, workspace and agent, read as the plugin starts. The sidebar
// hands the center the chat it selects, so the center draws without
// reading the list; the Ctrl+Tab switcher and the agents' names and marks
// need all of it. Nothing waits for this read, so a failure is reported here.
export const preloadChats = Effect.fn("Chat.preloadChats")(function* (c: Controller) {
  yield* Effect.forkIn(loadAgents(c), c.scope, { startImmediately: true });
  yield* loadChat(c).pipe(Effect.catch((error) => c.notify.error(`Chats could not be read: ${errorMessage(error)}`)));
});
export const loadAgents = Effect.fn("Chat.loadAgents")(function* (c: Controller) {
  // Every agent remains known for existing chats; pickers offer only enabled agents.
  yield* c.host.call("host/agents.all", {}).pipe(
    Effect.tap((result) => Effect.sync(() => {
      c.state.agentList = result.agents.filter((agent) => agent.enabled);
      for (const agent of result.agents) c.state.agents[agent.id] = agent;
      c.view.update();
      c.presentations?.updateAllTitles();
      c.updateSession();
      c.settingsView?.update();
    })),
    Effect.catch((error) => c.notify.error(`Agents could not be read: ${errorMessage(error)}`)),
  );
});
export const loadChat = Effect.fn("Chat.loadChat")(function* (
  c: Controller,
  chatId?: string,
): Effect.fn.Return<Chat | undefined, ChatError> {
  const [chats, workspaces] = yield* Effect.all(
    [c.host.call("host/chats.list", {}), c.host.call("host/workspaces.list", {})],
    { concurrency: "unbounded" },
  );
  // Keep chat changes that arrived after this list snapshot was taken.
  for (const chat of chats.chats) {
    const current = c.state.chats[chat.id];
    if (!current || current.updatedAt <= chat.updatedAt) c.state.chats[chat.id] = chat;
  }
  for (const workspace of workspaces.workspaces) c.state.workspaces[workspace.id] = workspace;
  yield* syncDraftTitles(c);
  yield* Effect.forkIn(c.pumpChatQueue(), c.scope, { startImmediately: true });
  c.center?.update();
  c.view.update();
  c.titleView?.update();
  c.updateSession();
  return chatId ? c.state.chats[chatId] : undefined;
});
export const loadWorkspaces = Effect.fn("Chat.loadWorkspaces")(function* (c: Controller) {
  const result = yield* c.host.call("host/workspaces.list", {});
  c.state.workspaces = Object.fromEntries(result.workspaces.map((workspace) => [workspace.id, workspace]));
  c.center?.update();
  c.presentations?.updateAllTitles();
  c.updateSession();
  for (const entry of Object.values(c.state.panes)) {
    const pane = registeredPane(entry);
    if (pane) c.updatePane(pane);
  }
});
/// Reconciles the chat with the agent's own record each time it shows: the
/// agent may have moved on in another program since (`chats.load_history`;
/// an unchanged record answers at once, and an older host reads only once per
/// app start). The pane shows the stored transcript meanwhile, with nothing
/// to say so, and a Send waits for it (`readyToSend`) under "Sends when
/// ready". A failure shows in the composer until dismissed or the next read,
/// and sending works again.
export const refreshHistory = Effect.fn("Chat.refreshHistory")(function* (c: Controller, chatId: string) {
  const chat = c.state.chats[chatId];
  if (!chat?.sessionId || c.state.transcripts[chatId]?.running || c.state.historyReading.has(chatId)) return;
  c.state.historyReading.add(chatId);
  // The composer may not exist yet (the read can start before the pane
  // renders); making it here must load its options as every other path does,
  // or it stays loading.
  yield* c.ensureComposer(chatId);
  const composer = c.composer(chatId);
  composer.syncing = true;
  composer.syncError = undefined;
  c.refresh(chatId);
  yield* c.host.call("host/chats.load_history", { chatId }).pipe(
    Effect.tap(() => Effect.sync(() => (composer.syncError = undefined))),
    Effect.catch((error) =>
      Effect.sync(() => {
        composer.syncError = `Could not sync with the agent's history: ${errorMessage(error)}`;
      }),
    ),
    Effect.ensuring(
      Effect.sync(() => {
        c.state.historyReading.delete(chatId);
        composer.syncing = false;
        c.refresh(chatId);
      }),
    ),
  );
});
function normalize(items: TranscriptItem[]) {
  for (const item of items) {
    if (item.role === "tool") {
      item.call.content ??= [];
      item.call.locations ??= [];
    }
    if (item.role === "task") normalize((item.items ??= []));
  }
}
export function reconcileOutgoing(c: Controller, chatId: string) {
  const composer = c.state.composers[chatId],
    outgoing = composer?.outgoing;
  if (!outgoing || !c.state.transcripts[chatId]?.items.some((item) => item.id === outgoing.id && item.role === "user"))
    return;
  composer.outgoing = undefined;
}
export type TranscriptLoadOptions = { readonly history?: boolean };
/** Which messages the host holds a checkpoint for, the only ones Revert is offered under: the host takes one only for a
 * prompt it dispatched while the setting is on, never for a steer. */
export const loadCheckpoints = Effect.fn("Chat.loadCheckpoints")(function* (c: Controller, chatId: string) {
  const transcript = c.transcript(chatId);
  yield* c.host.call("host/chats.checkpoints", { chatId }).pipe(
    Effect.tap((result) =>
      Effect.sync(() => {
        for (const checkpoint of result.checkpoints) transcript.checkpoints.add(checkpoint.itemId);
        c.refresh(chatId);
      }),
    ),
    Effect.catch((error) => c.notify.error(`Checkpoints unavailable: ${errorMessage(error)}`)),
  );
});
export const loadTranscript = Effect.fn("Chat.loadTranscript")(function* (
  c: Controller,
  chatId: string,
  options: TranscriptLoadOptions = {},
) {
  const transcript = c.transcript(chatId);
  // A send needs a read initiated after delivery, not an older in-flight snapshot.
  while (transcript.loading) yield* Deferred.await(transcript.loading);
  const loading = (transcript.loading = Deferred.makeUnsafe<void>());
  if (transcript.snapshot.kind === "failed") c.refresh(chatId);
  // Checkpoints annotate prompts; they must not delay installing the transcript snapshot.
  yield* Effect.forkIn(loadCheckpoints(c, chatId), c.scope, { startImmediately: true });
  const installed = yield* Effect.gen(function* () {
    while (c.state.transcripts[chatId] === transcript) {
      const version = transcript.version;
      const [result, answers] = yield* Effect.all(
        // The newest page (or as many rows as the pane already shows).
        [
          c.host.call("host/chats.transcript", { chatId, limit: Math.max(PAGE, transcript.items.length) }),
          c.answers.read(chatId),
        ],
        { concurrency: "unbounded" },
      );
      // A snapshot taken before a user message, delta or reset must not
      // erase that event. Read a fresh snapshot without blanking the pane.
      if (c.state.transcripts[chatId] !== transcript) return false;
      if (version !== transcript.version) continue;
      transcript.items = [...result.items];
      transcript.start = result.start ?? 0;
      transcript.lead = leadOf(result);
      normalize(transcript.items);
      transcript.earlierTasks = (result.liveTasks ?? []).filter((item) => item.role === "task");
      normalize(transcript.earlierTasks);
      if (transcript.start > 0 && transcript.items.length)
        transcript.rowsPerItem ??= rowCount(c, transcript.items) / transcript.items.length;
      transcript.sessions = { ...result.userSessions };
      // What each turn changed, in the same read: its summary draws with the rows.
      transcript.turnFiles = new Map(result.turnChanges?.map((turn) => [turn.itemId, turn]));
      for (const item of transcript.items) noteSession(transcript, item, c.state.chats[chatId]);
      reconcileOutgoing(c, chatId);
      transcript.approvals = [...result.pendingApprovals];
      transcript.questions = [...result.pendingQuestions];
      yield* c.answers.restore(chatId, answers);
      transcript.plan = result.plan;
      transcript.usage = result.usage;
      transcript.running = result.running;
      const inputs = c.scheduler.snapshots[chatId];
      readRun(transcript, inputs && (inputs.lastRun ? Date.parse(inputs.lastRun.stoppedAt) : -Infinity));
      transcript.snapshot = { kind: "ready" };
      c.refresh(chatId);
      if (allTasks(taskItems(transcript)).some((row) => isLive(row.task)))
        yield* Effect.forkIn(c.tickSubagents(), c.scope, { startImmediately: true });
      yield* c.loadImages(chatId);
      return true;
    }
    return false;
  }).pipe(
    Effect.catch((error) => Effect.sync(() => {
      transcript.snapshot = { kind: "failed", error: `Transcript unavailable: ${errorMessage(error)}` };
      return false;
    })),
    Effect.ensuring(
      Effect.gen(function* () {
        transcript.loading = undefined;
        c.refresh(chatId);
        c.presentations?.updateTitle(chatId);
        c.updateSession(chatId);
        yield* Deferred.succeed(loading, undefined);
      }),
    ),
  );
  // Prehydration reads the newest stored page without reconciling external history.
  if (options.history !== false)
    yield* Effect.forkIn(refreshHistory(c, chatId), c.scope, { startImmediately: true });
  return installed;
});
/** Rows the first read of a transcript holds: the newest, which draw first. */
export const PAGE = 50;

/** The message a page's first turn began with, read as the page's items are. */
function leadOf(page: { lead?: TranscriptItem | null }): TranscriptItem | undefined {
  if (!page.lead) return undefined;
  const lead = [page.lead];
  normalize(lead);
  return lead[0];
}
const rowCount = (c: Controller, items: TranscriptItem[]) =>
  entriesOf(withoutSpawnRows(items), c.api.settings.get("groupTools") !== false).length;
/** About how many rows the history not read yet would draw: the scroller
 * holds room for them (`rowsUnloaded`), so it is as tall as the whole chat
 * from its first page and a page read later takes room that was there. */
export function unreadRows(t: Transcript): number | undefined {
  return t.start > 0 && t.rowsPerItem ? Math.max(1, Math.round(t.start * t.rowsPerItem)) : undefined;
}
/** The items to read for a scroller that asked for the page before its rows
 * with its top `missing` rows into the room for unread history: a page, and
 * the rows it went past, so a jump far up is caught up in one read. */
export function olderLimit(t: Transcript, missing = 0): number {
  return PAGE + Math.ceil(missing / (t.rowsPerItem ?? 1));
}
/** One older page per scroller demand, of `limit` rows (Find in Chat reads
 * the rest of the chat at once). A newer snapshot supersedes a page read in
 * flight without losing the demand or changing the retained anchor. The
 * scroller asks again only once its row count changed, so a page whose rows
 * all go into the group already at the top (a long run of tool calls) is
 * followed by the next until one adds a row. */
export const loadOlder = Effect.fn("Chat.loadOlder")(function* (c: Controller, chatId: string, limit: number = PAGE) {
  const transcript = c.state.transcripts[chatId];
  if (!transcript || transcript.older) return;
  transcript.older = true;
  const ready = transcript.olderReady = Deferred.makeUnsafe<void>();
  const rows = () => rowCount(c, transcript.items);
  const installed = yield* Effect.gen(function* () {
    while (c.state.transcripts[chatId] === transcript) {
      while (transcript.loading) yield* Deferred.await(transcript.loading);
      if (c.state.transcripts[chatId] !== transcript || transcript.snapshot.kind === "unread" || transcript.start <= 0) return false;
      const { start, version } = transcript;
      const result = yield* c.host.call("host/chats.transcript", { chatId, limit, before: start });
      if (c.state.transcripts[chatId] !== transcript) return false;
      if (transcript.loading || transcript.version !== version || transcript.start !== start) continue;
      const older = [...result.items];
      normalize(older);
      Object.assign(transcript.sessions, result.userSessions);
      for (const turn of result.turnChanges ?? [])
        if (!transcript.turnFiles.has(turn.itemId)) transcript.turnFiles.set(turn.itemId, turn);
      for (const item of older) noteSession(transcript, item, c.state.chats[chatId]);
      carryFold(transcript.folds, older, transcript.items[0]);
      const shown = rows();
      transcript.items = [...older, ...transcript.items];
      transcript.earlierTasks = transcript.earlierTasks.filter((task) => !older.some((item) => item.id === task.id));
      transcript.start = result.start ?? 0;
      transcript.lead = leadOf(result);
      c.refresh(chatId);
      if (transcript.start > 0 && rows() === shown) continue;
      return true;
    }
    return false;
  }).pipe(
    Effect.catch((error) => c.notify.error(`Older messages unavailable: ${errorMessage(error)}`).pipe(Effect.as(false))),
    Effect.ensuring(Effect.gen(function* () {
      transcript.older = false;
      transcript.olderReady = undefined;
      yield* Deferred.succeed(ready, undefined);
    })),
  );
  // Image retrieval cannot hold admission closed when the next viewport asks for a page.
  if (installed) yield* c.loadImages(chatId);
});
export const loadRequests = Effect.fn("Chat.loadRequests")(function* (c: Controller, chatId: string) {
  yield* c.host.call("host/security.pending", { chatId }).pipe(
    Effect.tap((result) =>
      Effect.sync(() => {
        c.transcript(chatId).requests = result.requests;
        c.refresh(chatId);
      }),
    ),
    Effect.catch((error) => Effect.logWarning(`security requests unavailable: ${errorMessage(error)}`)),
  );
});
export const tickSubagents = Effect.fn("Chat.tickSubagents")(function* (c: Controller) {
  if (c.state.ticking) return;
  c.state.ticking = true;
  yield* Effect.gen(function* () {
    for (;;) {
      yield* Effect.sleep(1000);
      const live = Object.entries(c.state.transcripts).filter(([, transcript]) =>
        allTasks(transcript.items).some((row) => isLive(row.task) && row.task.startedAt),
      );
      if (!live.length) return;
      for (const [chatId] of live) {
        c.refreshSubagentTabs(chatId);
        // Every pane on screen counts on, a split pane that is not selected too.
        if (c.shown(chatId)) c.refresh(chatId);
        c.updateSession(chatId);
      }
    }
  }).pipe(
    Effect.ensuring(
      Effect.sync(() => {
        c.state.ticking = false;
      }),
    ),
  );
});

export function errorMessage(error: { message: string } | { what: string; issues: readonly string[] }): string {
  const text = "message" in error ? error.message : `${error.what}: ${error.issues.join("; ")}`;
  if (text.trim()) return text;
  // An error that says nothing still says what kind it is, so a notice
  // never reads "Edit failed: ".
  const tag = (error as { _tag?: unknown })._tag;
  return typeof tag === "string" && tag ? `an unknown error (${tag})` : "an unknown error";
}

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.