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

Permissions in 0.2.8

  • 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

composer.ts38.6 KB
// Request failures recover at the same notification/logging boundaries as the JavaScript baseline.
// Composer actions preserve per-chat drafts, inline mention segments and both prompt queues.
// Submission clears immediately; its local preview hands ownership to host
// evidence, and capture failures restore the draft without erasing later edits.
import * as Effect from "effect/Effect";
import type { AttachedImage, Chat, PasteEvent, SubmitEvent, Workspace } from "divergence";
import type { Prompt, Waiting } from "./state.ts";
import type { Controller, ChatError } from "./controller.ts";
import { keepSegments } from "./mentions.ts";
import { fromTokens, followEdit, insertSegment, removeRange, triggerAt, withFiles } from "./segments.ts";
import { APP_COMMANDS, runAppCommand } from "./app-commands.ts";
import { entries, highlighted, segmentsOf, type Entry } from "./picker.ts";
import { amendedInput, blocksFor, compositionFor, inputId, steeringReason } from "./composition.ts";
import {
  announceQueued,
  errorMessage,
  loadOptions,
  persistQueues,
  setStarting,
  syncDraftTitle,
  textChanged,
} from "./data.ts";

const IMAGE_FILE = /\.(png|jpe?g|gif|webp|bmp|tiff?|ico|svg)$/i;
// What the prompt box shows of its text besides the text itself: Send or
// Stop and whether the arrows go through the chat's earlier prompts
// (`history.ts`). The prompt draws the typed text, and colours its
// keywords, on its own, so a key that changes neither of these draws only
// there, without a render of the composer in between.
function shownOf(c: Controller, chatId: string, text: string) {
  const recalled = c.composer(chatId).recalled?.text === text;
  return [!!text.trim(), recalled].join("\n");
}
/// What the prompt field says with its text: where the caret is and where
/// its pills are. An older kernel says neither.
export type FieldChange = { caret?: number; tokens?: readonly { id: string; start: number; end: number }[] };
/// Where two texts first differ: where an edit starts.
function firstDifference(a: string, b: string) {
  let at = 0;
  while (at < a.length && a[at] === b[at]) at++;
  return at;
}
export const onChange = Effect.fn("Chat.onChange")(function* (
  c: Controller,
  chatId: string,
  text: string,
  field: FieldChange = {},
) {
  const composer = c.composer(chatId),
    mentions = c.api.mentions.list();
  const before = composer.text,
    shown = shownOf(c, chatId, before),
    segments = segmentsOf(c, composer);
  // The field keeps its pills whole itself. Without it (an older kernel)
  // a deletion that cuts into a mention tag takes all of it here, and the
  // caret stays where the tag was.
  const kept = field.tokens ? text : keepSegments(before, text, mentions);
  composer.text = kept;
  composer.segments = { text: kept, list: field.tokens ? fromTokens(field.tokens) : followEdit(before, kept, segments) };
  composer.caret = kept === text ? (field.caret ?? text.length) : firstDifference(before, kept);
  if (kept !== text) composer.place = { text: kept, at: composer.caret };
  if (shownOf(c, chatId, kept) !== shown) c.refreshComposer(chatId);
  yield* textChanged(c, chatId);
  if (kept !== text) {
    composer.picker = null;
    c.refreshComposer(chatId);
    return;
  }
  yield* openPicker(c, chatId);
});
/// Opens the picker for the word at the caret (`triggerAt`), or closes it.
/// A word whose picker Escape closed stays closed while it is typed on.
const openPicker = Effect.fn("Chat.openPicker")(function* (c: Controller, chatId: string) {
  const composer = c.composer(chatId),
    open = composer.picker;
  const trigger = triggerAt(composer.text, composer.caret ?? composer.text.length, segmentsOf(c, composer));
  if (!trigger || trigger.start !== composer.dismissed) composer.dismissed = undefined;
  if (!trigger || composer.dismissed !== undefined) {
    if (open) {
      composer.picker = null;
      c.refreshComposer(chatId);
    }
    return;
  }
  const kind =
    trigger.sigil === "@" ? "files" : trigger.sigil === "$" ? "skills" : trigger.start === 0 ? "commands" : "slash";
  const { start, end, query } = trigger;
  composer.picker = { kind, query, start, end };
  if (kind === "files" && !(open?.kind === "files" && open.query === query)) {
    const chat = c.state.chats[chatId];
    if (chat)
      yield* Effect.forkIn(
        c.host.call("host/fs.search", { workspaceId: chat.workspaceId, query, limit: 10, folders: true }).pipe(
          Effect.match({
            onSuccess: (result) => ({ files: result.paths, error: undefined }),
            onFailure: (error) => ({ files: [], error: `Could not search files: ${errorMessage(error)}` }),
          }),
          // Only the answer for what is typed now: an older query's never
          // replaces newer results. Until it comes the list keeps the last.
          Effect.map(({ files, error }) => {
            const picker = composer.picker;
            if (picker?.kind !== "files" || picker.query !== query) return;
            // A row the keys moved to stays highlighted as the rows change under it.
            const listed = entries(c, composer),
              moved = picker.index ? listed[highlighted(composer, listed.length)]?.id : undefined;
            composer.files = files;
            composer.filesFor = query;
            composer.filesError = error;
            if (moved) picker.index = Math.max(0, entries(c, composer).findIndex((entry) => entry.id === moved));
            c.refreshComposer(chatId);
          }),
        ),
        c.scope,
        { startImmediately: true },
      );
  }
  c.refreshComposer(chatId);
});
/// Takes a picker entry: its pill replaces the picker's word, and the
/// caret goes after it. Enter runs a command that takes no input; Tab
/// (`run` false) only completes it.
export const acceptEntry = Effect.fn("Chat.acceptEntry")(function* (
  c: Controller,
  chatId: string,
  entry: Entry,
  run = true,
) {
  const composer = c.composer(chatId),
    picker = composer.picker;
  if (!picker) return;
  // The app's own command leaves nothing in the text: its word goes, and
  // what it opens takes over (the settings menu, the title field).
  const next = entry.app
    ? removeRange(composer.text, segmentsOf(c, composer), picker)
    : insertSegment(composer.text, segmentsOf(c, composer), picker, entry.kind, entry.text);
  composer.text = next.text;
  composer.segments = { text: next.text, list: next.segments };
  if (entry.kind === "file" && !entry.app) composer.tagged = withFiles(composer.tagged, [entry.text.slice(1)]);
  composer.caret = next.caret;
  composer.place = { text: next.text, at: next.caret };
  composer.picker = null;
  yield* textChanged(c, chatId);
  if (entry.app) {
    c.refreshComposer(chatId);
    yield* runAppCommand(c, chatId, entry.app);
  } else if (run && entry.command && !entry.command.inputHint)
    yield* Effect.forkIn(send(c, chatId), c.scope, { startImmediately: true });
  else c.refreshComposer(chatId);
});
// A reply to part of a message: the part as a quote after what is typed,
// separated from existing text, with the caret on the line below it.
export function withQuote(text: string, quote: string) {
  const typed = text.trimEnd();
  const quoted = quote
    .split("\n")
    .map((line) => (line ? `> ${line}` : ">"))
    .join("\n");
  return `${typed}${typed ? "\n\n" : ""}${quoted}\n`;
}
export const quote = Effect.fn("Chat.quote")(function* (c: Controller, chatId: string, text: string) {
  const composer = c.composer(chatId),
    list = segmentsOf(c, composer);
  // The quote goes after what is typed: the pills stay where they are.
  composer.text = withQuote(composer.text, text);
  composer.segments = { text: composer.text, list };
  yield* textChanged(c, chatId);
  c.refreshComposer(chatId);
  yield* c.views.focus(`prompt-${chatId}`);
});
// A reply from outside a transcript, such as to code in a tab, goes to the
// chat on screen.
export const quoteInOpenChat = Effect.fn("Chat.quoteInOpenChat")(function* (c: Controller, text: string) {
  const { chatId, route } = c.api.app.state();
  if (!chatId) return yield* Effect.fail({ _tag: "NoOpenChat" as const, message: "Open a chat to reply in." });
  if (typeof route === "string" && route !== "chat") yield* c.app.route("chat");
  yield* quote(c, chatId, text);
});
export const keepNewImages = Effect.fn("Chat.keepNewImages")(function* (
  c: Controller,
  chatId: string,
  images: readonly AttachedImage[],
) {
  const composer = c.composer(chatId);
  // File selection/paste may finish after a handoff has committed a queue
  // entry into the empty draft. Install that draft before accepting images.
  while (composer.preparing) yield* Effect.sleep(10);
  for (const image of images) {
    if (composer.attachments.some((held) => held.id === image.id))
      yield* c.kernel.call("forget_image", { id: image.id });
    else {
      composer.attachments.push(image);
      composer.editVersion = (composer.editVersion ?? 0) + 1;
    }
  }
  yield* Effect.forkIn(c.saveUnsent(), c.scope, { startImmediately: true });
});
export const refuseImages = Effect.fn("Chat.refuseImages")(function* (
  c: Controller,
  chatId: string,
  attached: readonly AttachedImage[],
) {
  for (const image of attached) yield* c.kernel.call("forget_image", { id: image.id });
  const chat = c.state.chats[chatId],
    name = chat ? (c.state.agents[chat.agentId]?.name ?? "This agent") : "This agent";
  yield* c.notify.warning(`${name} cannot read images`);
});
export const attachFiles = Effect.fn("Chat.attachFiles")(function* (
  c: Controller,
  chatId: string,
  paths: readonly string[],
) {
  const composer = c.composer(chatId),
    mentions = paths.filter((path) => !IMAGE_FILE.test(path));
  while (composer.preparing) yield* Effect.sleep(10);
  if (mentions.length) {
    const list = [...segmentsOf(c, composer)];
    let text = composer.text && !composer.text.endsWith(" ") ? `${composer.text} ` : composer.text;
    for (const path of mentions) {
      list.push({ start: text.length, end: text.length + 1 + path.length, kind: "file" });
      text += `@${path} `;
    }
    composer.text = text;
    composer.segments = { text, list };
    // A dropped path may hold spaces: the send reads it whole only as a tagged one.
    composer.tagged = withFiles(composer.tagged, mentions);
    yield* textChanged(c, chatId);
  }
  const images = paths.filter((path) => IMAGE_FILE.test(path));
  if (images.length && !c.takesImages(chatId)) {
    c.view.update();
    return yield* refuseImages(c, chatId, []);
  }
  c.view.update();
  for (const path of images)
    yield* c.kernel.call("attach_image", { path }).pipe(
      Effect.flatMap((image) => keepNewImages(c, chatId, [image])),
      Effect.catch((error) => c.notify.error(`Could not attach ${path}: ${errorMessage(error)}`)),
    );
  c.view.update();
});
export const onPasteFiles = Effect.fn("Chat.onPasteFiles")(function* (
  c: Controller,
  chatId: string,
  event: PasteEvent,
) {
  const images = event.images ?? [];
  if (images.length) yield* c.takesImages(chatId) ? keepNewImages(c, chatId, images) : refuseImages(c, chatId, images);
  for (const reason of event.refused ?? []) yield* c.notify.error(`Could not attach: ${reason}`);
  if (event.paths?.length)
    yield* Effect.forkIn(attachFiles(c, chatId, event.paths), c.scope, { startImmediately: true });
  c.view.update();
});
export const removeAttachment = Effect.fn("Chat.removeAttachment")(function* (
  c: Controller,
  chatId: string,
  id: string,
) {
  const composer = c.composer(chatId);
  composer.attachments = composer.attachments.filter((image) => image.id !== id);
  composer.editVersion = (composer.editVersion ?? 0) + 1;
  yield* c.kernel.call("forget_image", { id });
  yield* Effect.forkIn(c.saveUnsent(), c.scope, { startImmediately: true });
  c.view.update();
});
export const pickAttachments = Effect.fn("Chat.pickAttachments")(function* (c: Controller, chatId: string) {
  if (!c.takesImages(chatId)) return yield* refuseImages(c, chatId, []);
  yield* c.kernel.call("pick_images", {}).pipe(
    Effect.flatMap(({ paths }) => (paths.length ? attachFiles(c, chatId, paths) : Effect.void)),
    Effect.catch((error) => c.notify.error(`Could not attach: ${errorMessage(error)}`)),
  );
});
export function pickerKey(c: Controller, chatId: string, key: string) {
  const composer = c.composer(chatId),
    picker = composer.picker;
  if (!picker) return;
  if (key === "escape") {
    composer.dismissed = picker.start;
    composer.picker = null;
  } else if (key === "up" || key === "down") {
    const count = entries(c, composer).length;
    if (count) picker.index = (highlighted(composer, count) + (key === "up" ? -1 : 1) + count) % count;
  } else return;
  c.refreshComposer(chatId);
}
export const onSubmit = Effect.fn("Chat.onSubmit")(function* (
  c: Controller,
  chatId: string,
  event?: SubmitEvent,
): Effect.fn.Return<void, ChatError> {
  const composer = c.composer(chatId);
  if (event?.shift) return;
  if (event && typeof event.value === "string") composer.text = event.value;
  if (event?.secondary) {
    // This never accepts a highlighted candidate on the user's behalf.
    if (
      composer.picker?.kind === "commands" &&
      !c.commandList(composer).some((command) => composer.text.trim() === `/${command.name}`) &&
      !APP_COMMANDS.has(composer.text.trim().slice(1))
    )
      return yield* c.notify.warning("Choose a complete command before queueing");
    // A draft has no prompt queue: its first prompt queues the chat.
    const chat = c.state.chats[chatId];
    if (chat && c.isDraft(chat))
      return c.state.chatQueue.some((queued) => queued.chatId === chatId) ? undefined : yield* queueChat(c, chatId);
    return yield* queuePrompt(c, chatId);
  }
  if (!(yield* acceptPicked(c, chatId))) yield* send(c, chatId);
});
/// Takes the picker's highlighted entry; false when it lists none.
export const acceptPicked = Effect.fn("Chat.acceptPicked")(function* (c: Controller, chatId: string, run = true) {
  const composer = c.composer(chatId),
    listed = entries(c, composer),
    entry = listed[highlighted(composer, listed.length)];
  if (entry) yield* acceptEntry(c, chatId, entry, run);
  return !!entry;
});
export const sendBlocks = Effect.fn("Chat.sendBlocks")(function* (
  c: Controller,
  chatId: string,
  text: string,
  attachments: Prompt["attachments"],
) {
  const blocks = yield* blocksFor(c, chatId, text, attachments);
  if (!blocks.length) return;
  if (c.scheduler.available === undefined) yield* c.scheduler.load(chatId);
  if (c.scheduler.available === false) yield* c.host.call("host/chats.send", { chatId, blocks });
  else {
    const id = inputId(),
      snapshot = yield* c.scheduler.enqueue(chatId, id, blocks, c.isRunning(c.state.chats[chatId]) ? "steer" : "send");
    const entry = amendedInput(snapshot, id);
    if (entry) yield* c.scheduler.manualDispatch(chatId, entry.id, snapshot.revision);
  }
});
function readyToSend(c: Controller, chatId: string) {
  const composer = c.composer(chatId);
  return (
    !composer.loading &&
    !composer.preparing &&
    !composer.syncing &&
    !c.drafts.loading.has(chatId) &&
    !c.scheduler.snapshots[chatId]?.preparing
  );
}

/// Sends the prompts Enter took from the box, in order, as the chat becomes
/// ready for each; nothing once the chat went away.
const sendWhenReady = Effect.fn("Chat.sendWhenReady")(function* (c: Controller, chatId: string) {
  const composer = c.composer(chatId);
  let next: Waiting | undefined;
  while (c.state.chats[chatId] && (next = composer.waiting?.[0])) {
    if (!readyToSend(c, chatId) || composer.submitting) {
      yield* Effect.sleep(SEND_WHEN_READY_POLL);
      continue;
    }
    const rest = composer.waiting?.slice(1);
    composer.waiting = rest?.length ? rest : undefined;
    c.refresh(chatId);
    yield* submitComposition(c, chatId, next.queue, next);
  }
});
/// A chat whose waiting sends are all gone, sent or given back, is no longer
/// starting on their account; a send under way clears its own mark.
function endWaiting(c: Controller, chatId: string) {
  const composer = c.composer(chatId);
  if (!composer.submitting && !composer.waiting?.some((waiting) => !waiting.queue)) setStarting(c, chatId, false);
}
/// A prompt the chat did not take goes back where the user can see it:
/// into the box when that is empty, where it is saved as the draft,
/// otherwise beside it to restore.
export const giveBack = Effect.fn("Chat.giveBack")(function* (
  c: Controller,
  chatId: string,
  prompt: Omit<Waiting, "queue">,
) {
  const composer = c.composer(chatId);
  if (!composer.text && !composer.attachments.length) {
    composer.text = prompt.text;
    composer.attachments = prompt.attachments;
    composer.carriedBlocks = prompt.carriedBlocks;
    yield* textChanged(c, chatId);
  } else (composer.recovered ??= []).push({ ...prompt, submission: { id: inputId(), signature: "" } });
  c.refresh(chatId);
});
/// Cancelling a waiting prompt keeps its text: it goes back to the box.
export const takeBack = Effect.fn("Chat.takeBack")(function* (c: Controller, chatId: string, prompt: Waiting) {
  const composer = c.composer(chatId);
  const rest = composer.waiting?.filter((waiting) => waiting !== prompt);
  composer.waiting = rest?.length ? rest : undefined;
  endWaiting(c, chatId);
  yield* giveBack(c, chatId, prompt);
});
const SEND_WHEN_READY_POLL = "100 millis";

export const submitComposition = Effect.fn("Chat.submitComposition")(function* (
  c: Controller,
  chatId: string,
  queue: boolean,
  prompt?: Waiting,
): Effect.fn.Return<void, ChatError> {
  const composer = c.composer(chatId),
    chat = c.state.chats[chatId];
  if (!chat || (!prompt && composer.submitting)) return;
  // The chat is not ready to send yet (the host is resuming its session
  // after a relaunch, its options load) or earlier prompts wait for it: the
  // prompt leaves the box at once and waits over it, then goes by itself.
  if (!prompt && (!readyToSend(c, chatId) || composer.waiting?.length)) {
    if (!composer.text.trim() && !composer.attachments.length && !composer.carriedBlocks?.length) return;
    const first = !composer.waiting?.length;
    (composer.waiting ??= []).push({
      queue,
      text: composer.text,
      attachments: [...composer.attachments],
      carriedBlocks: [...(composer.carriedBlocks ?? [])],
    });
    composer.text = "";
    composer.attachments = [];
    composer.carriedBlocks = [];
    composer.picker = null;
    // A send to an idle chat starts its run as Enter takes it, waiting or not: the sidebar moves it now.
    if (!queue && !c.isRunning(chat)) setStarting(c, chatId, true);
    c.refresh(chatId);
    if (first)
      yield* Effect.forkIn(sendWhenReady(c, chatId).pipe(Effect.ensuring(Effect.sync(() => endWaiting(c, chatId)))), c.scope, {
        startImmediately: true,
      });
    return;
  }
  const source = prompt ?? { text: composer.text, attachments: composer.attachments, carriedBlocks: composer.carriedBlocks ?? [] };
  const text = source.text.trim(),
    originalText = source.text,
    attachments = [...source.attachments],
    carriedBlocks = [...source.carriedBlocks];
  if (!text && !attachments.length && !carriedBlocks.length) return;
  const reason = !queue && steeringReason(c, chat);
  if (reason) {
    if (prompt) yield* giveBack(c, chatId, prompt);
    return yield* c.notify.warning(reason);
  }
  const signature = JSON.stringify([text, attachments.map((image) => image.id), carriedBlocks, queue]);
  const retry = composer.submission?.signature === signature;
  if (composer.submission?.signature !== signature)
    composer.submission = { id: c.drafts.snapshots[chatId]?.inputId ?? inputId(), signature };
  const id = composer.submission.id;
  const outgoing = (composer.outgoing = {
    id,
    text,
    attachments,
    preview: !queue && !c.isRunning(chat) && !text.startsWith("/") && c.scheduler.available === true,
    intent: queue ? "queue" : c.isRunning(chat) ? "steer" : undefined,
    blocks: [{ type: "text", text }, ...carriedBlocks],
  });
  const editVersion = composer.editVersion ?? 0;
  composer.submitting = true;
  if (!queue) composer.sent = (composer.sent ?? 0) + 1;
  composer.error = undefined;
  if (!prompt) {
    composer.text = "";
    composer.attachments = [];
    composer.carriedBlocks = [];
    composer.picker = null;
  }
  let acknowledged = false;
  // A send to an idle chat starts a run: the sidebar shows it running now,
  // with the prompt box, not when the host reports it.
  if (!outgoing.intent) setStarting(c, chatId, true);
  c.refresh(chatId);
  yield* Effect.gen(function* () {
    if (c.scheduler.available === undefined) yield* c.scheduler.load(chatId);
    if (c.scheduler.available === false) outgoing.preview = false;
    const { blocks, composition } = yield* compositionFor(c, chatId, originalText, attachments, carriedBlocks);
    if (composer.outgoing?.preview) composer.outgoing.blocks = blocks;
    let dispatch: { id: string; revision: number } | undefined;
    if (c.scheduler.available === false) {
      if (queue) {
        composer.queue.push({ text, attachments: [], blocks, id });
        const saved = yield* persistQueues(c).pipe(Effect.result);
        if (saved._tag === "Failure") {
          composer.queue = composer.queue.filter((input) => input.id !== id);
          return yield* Effect.fail(saved.failure);
        }
      } else {
        // Alpha's original idle send path. Never fall back on an ambiguous new
        // host failure: only a positively unknown method selects this path.
        const [name = "", ...rest] = text.slice(1).split(/\s+/);
        if (text.startsWith("/") && c.api.slashCommands().some((command) => command.name === name)) {
          const result = yield* importSlash(c, name, rest.join(" "), {
            chatId,
            workspaceId: chat.workspaceId,
            agentId: chat.agentId,
          });
          if (result.action === "prompt")
            yield* c.host.call("host/chats.send", {
              chatId,
              blocks: [{ type: "text", text: result.text }, ...blocks.filter((block) => block.type !== "text")],
            });
          else if (result.action === "message") yield* c.notify.info(result.text);
        } else yield* c.host.call("host/chats.send", { chatId, blocks });
      }
    } else {
      // Slash text is durable intent. The host resolves commands/hooks once,
      // including deferred non-prompt commands; the UI never resolves it twice.
      const existing = retry ? (yield* c.scheduler.read(chatId)).inputs.find((input) => input.id === id) : undefined;
      const draft = existing ? undefined : yield* c.drafts.capture(chatId, blocks, composition);
      const snapshot = yield* c.scheduler.enqueue(
        chatId,
        id,
        blocks,
        queue ? "queue" : c.isRunning(chat) ? "steer" : "send",
        "user",
        draft?.revision,
      );
      const entry = amendedInput(snapshot, id);
      if (!queue && entry && (entry.state === "held" || entry.state === "rejected"))
        dispatch = { id: entry.id, revision: snapshot.revision };
    }
    acknowledged = true;
    // An acknowledged steer is the host's now: while the agent takes it, the prompt box is free
    // for the next one. A send to an idle chat keeps it until its run shows.
    if (outgoing.intent) composer.submitting = false;
    // Clearing the acknowledged composition is an edit too. Otherwise a retry
    // can leave its restored text in the durable draft after the UI empties.
    if ((composer.editVersion ?? 0) === editVersion) composer.editVersion = editVersion + 1;
    if (!outgoing.preview && !outgoing.intent) composer.outgoing = undefined;
    if (!queue) yield* unqueueChat(c, chatId);
    composer.submission = undefined;
    yield* syncDraftTitle(c, chatId);
    yield* Effect.forkIn(c.saveUnsent(), c.scope, { startImmediately: true });
    c.refresh(chatId);
    if (dispatch) {
      const id = dispatch.id;
      composer.dispatching = id;
      yield* c.scheduler.manualDispatch(chatId, id, dispatch.revision).pipe(
        Effect.ensuring(
          Effect.sync(() => {
            if (composer.dispatching === id) composer.dispatching = undefined;
          }),
        ),
      );
      if (composer.outgoing?.preview) {
        // The RPC can finish before the user-message listener. Keep one visible
        // copy until a post-delivery snapshot or that exact event takes over.
        const installed = yield* c.loadTranscript(chatId);
        if (!installed || composer.outgoing) {
          composer.error = installed
            ? "Input submitted; transcript did not contain the message"
            : "Input submitted; transcript refresh failed";
          yield* c.notify.error(composer.error);
        }
      }
    }
  }).pipe(
    Effect.catch((error) =>
      Effect.gen(function* () {
        if (!acknowledged) {
          if ((composer.editVersion ?? 0) === editVersion && !composer.text && !composer.attachments.length) {
            composer.text = originalText;
            composer.attachments = attachments;
            composer.carriedBlocks = carriedBlocks;
          } else
            (composer.recovered ??= []).push({
              text: originalText,
              attachments,
              carriedBlocks,
              submission: { id, signature },
            });
          yield* syncDraftTitle(c, chatId);
        }
        composer.error = `Input could not be submitted: ${errorMessage(error)}`;
        if (composer.outgoing === outgoing) composer.outgoing = undefined;
        c.refresh(chatId);
        yield* c.notify.error(composer.error);
        if (c.scheduler.available === true) yield* c.scheduler.load(chatId);
        if (!acknowledged && c.drafts.available === true)
          yield* c.drafts
            .read(chatId)
            .pipe(Effect.catch((failure) => c.notify.error(`Draft refresh failed: ${errorMessage(failure)}`)));
      }),
    ),
    Effect.ensuring(
      Effect.gen(function* () {
        // A later input may be on its way already, once a steer was acknowledged.
        if (composer.outgoing === outgoing) composer.outgoing = undefined;
        if (!acknowledged || !outgoing.intent) composer.submitting = false;
        setStarting(c, chatId, false);
        c.refresh(chatId);
        yield* c.drafts
          .save(chatId)
          .pipe(Effect.catch((error) => c.notify.error(`Draft could not be saved: ${errorMessage(error)}`)));
        if (acknowledged)
          for (const image of attachments) {
            yield* c.kernel
              .call("forget_image", { id: image.id })
              .pipe(Effect.catch((error) => c.notify.warning(`Image cleanup: ${errorMessage(error)}`)));
          }
        c.refresh(chatId);
      }),
    ),
  );
});
// External controls use the same composition as the chat, without navigating
// to it. A draft never opened this session still needs its content and options.
export const submitDraft = Effect.fn("Chat.submitDraft")(function* (c: Controller, chatId: string, queue: boolean) {
  yield* Effect.gen(function* () {
    if (!c.state.chats[chatId]) yield* c.loadChat(chatId);
    yield* c.drafts.load(chatId);
    if (c.composer(chatId).loading) yield* c.loadOptions(chatId);
    yield* queue ? queueChat(c, chatId) : send(c, chatId);
  }).pipe(Effect.catch((error) => c.notify.error(`Input could not be submitted: ${errorMessage(error)}`)));
  return null;
});
export const send = Effect.fn("Chat.send")((c: Controller, chatId: string) => submitComposition(c, chatId, false));
// Slash dispatch is a plugin-local callback API rather than a host method.
import { promise } from "divergence/effect";
const importSlash = Effect.fn("Chat.runSlash")(
  (c: Controller, name: string, input: string, context: { chatId: string; workspaceId: string; agentId: string }) =>
    promise("slash.run", () => c.api.runSlash(name, input, context)),
);
export const queuePrompt = Effect.fn("Chat.queuePrompt")((c: Controller, chatId: string) =>
  submitComposition(c, chatId, true),
);
export const dropQueuedPrompt = Effect.fn("Chat.dropQueuedPrompt")(function* (
  c: Controller,
  chatId: string,
  index: number,
) {
  const composer = c.composer(chatId),
    removed = composer.queue.splice(index, 1);
  yield* persistQueues(c).pipe(
    Effect.catch((error) =>
      Effect.gen(function* () {
        composer.queue.splice(index, 0, ...removed);
        yield* c.notify.error(`Queue could not be saved: ${errorMessage(error)}`);
      }),
    ),
  );
  c.view.update();
});
export const sendText = Effect.fn("Chat.sendText")(function* (c: Controller, chatId: string, text: string) {
  const chat = c.state.chats[chatId];
  yield* c.host
    .call("host/chats.send", { chatId, text })
    .pipe(Effect.catch((error) => c.notify.error(`Send failed: ${errorMessage(error)}`)));
  return chat;
});
// A queued draft stays a draft: its prompt stays in the composer, where it
// can still change, and is sent when no chat runs.
export const queueChat = Effect.fn("Chat.queueChat")(function* (c: Controller, chatId: string) {
  const composer = c.composer(chatId);
  if (!composer.text.trim() && !composer.attachments.length && !composer.carriedBlocks?.length) return;
  if (c.state.chatQueue.some((queued) => queued.chatId === chatId)) return;
  c.state.chatQueue.push({ chatId });
  yield* Effect.forkIn(persistQueues(c), c.scope, { startImmediately: true });
  yield* announceQueued(c);
  c.view.update();
  yield* Effect.forkIn(pumpChatQueue(c), c.scope, { startImmediately: true });
});
export const unqueueChat = Effect.fn("Chat.unqueueChat")(function* (c: Controller, chatId: string) {
  if (!c.state.chatQueue.some((queued) => queued.chatId === chatId)) return;
  c.state.chatQueue = c.state.chatQueue.filter((queued) => queued.chatId !== chatId);
  yield* Effect.forkIn(persistQueues(c), c.scope, { startImmediately: true });
  yield* announceQueued(c);
  c.view.update();
});
// Starts the first queued draft once no chat runs. Called whenever a chat
// changes; one draft starts at a time, as the started one then runs.
export const pumpChatQueue = Effect.fn("Chat.pumpChatQueue")(function* (c: Controller) {
  while (true) {
    if (c.state.releasing || Object.values(c.state.chats).some((chat) => !chat.archived && c.isRunning(chat))) return;
    const next = c.state.chatQueue[0];
    // The chat list is not read yet: whether a chat runs is not known.
    if (!next || !c.state.chats[next.chatId]) return;
    // Queue entries hold identity; hydrate their durable composition before
    // deciding whether there is anything to send after a restart.
    c.state.releasing = next.chatId;
    const loaded = yield* c.drafts.load(next.chatId).pipe(Effect.result);
    if (loaded._tag === "Failure") {
      c.state.releasing = null;
      yield* c.notify.error(`Queued draft unavailable: ${errorMessage(loaded.failure)}`);
      return;
    }
    yield* unqueueChat(c, next.chatId);
    const composer = c.composer(next.chatId);
    // A prompt emptied while it waited has nothing to start.
    if (!composer.text.trim() && !composer.attachments.length && !composer.carriedBlocks?.length) {
      c.state.releasing = null;
      continue;
    }
    if (composer.loading) yield* loadOptions(c, next.chatId);
    yield* send(c, next.chatId);
    // A sent prompt holds the queue until the host reports the chat running.
    // A failed send leaves the draft and its error in place, and a command
    // that started no run (the host's dispatch answers not running) never
    // runs: the queue moves on after either.
    const started = c.scheduler.available !== true || !!c.scheduler.snapshots[next.chatId]?.running;
    if (!composer.error && started) return;
    c.state.releasing = null;
  }
});
export const setOption = Effect.fn("Chat.setOption")(function* (
  c: Controller,
  chatId: string,
  optionId: string,
  value: string | boolean,
) {
  const composer = c.composer(chatId);
  if (composer.options.find((option) => option.id === optionId)?.value === value) return;
  const changed = yield* c.host.call("host/chats.set_option", { chatId, optionId, value }).pipe(
    Effect.tap((result) =>
      Effect.sync(() => {
        composer.options = result.options;
        c.view.update();
      }),
    ),
    Effect.as(true),
    Effect.catch((error) =>
      c.notify.error(`Could not change the option: ${errorMessage(error)}`).pipe(Effect.as(false)),
    ),
  );
  if (!changed) return;
  const agentId = c.state.chats[chatId]?.agentId;
  for (const [id, draft] of Object.entries(c.state.composers)) {
    const chat = c.state.chats[id];
    if (id !== chatId && !draft.loading && chat?.agentId === agentId && !chat?.sessionId)
      yield* Effect.forkIn(loadOptions(c, id), c.scope, { startImmediately: true });
  }
});
export const changeAgent = Effect.fn("Chat.changeAgent")(function* (c: Controller, chatId: string, agentId: string) {
  const chat = c.state.chats[chatId],
    composer = c.composer(chatId);
  if (!chat || chat.agentId === agentId || composer.preparing || composer.submitting || c.isRunning(chat)) return;
  composer.preparing = true;
  c.refresh(chatId);
  let before: import("divergence").ComposerDraft | undefined;
  let version = composer.editVersion ?? 0;
  let attempted = false;
  let reconciled = true;
  yield* Effect.gen(function* () {
    yield* c.drafts.save(chatId);
    if (!chat.sessionId && !c.transcript(chatId).items.length) {
      c.state.chats[chatId] = yield* c.host.call("host/chats.update", { chatId, agentId });
      // An agent that cannot read images gets none: the chips go as a drop would be refused.
      if (composer.attachments.length && !c.takesImages(chatId)) {
        const refused = composer.attachments;
        composer.attachments = [];
        yield* textChanged(c, chatId);
        yield* refuseImages(c, chatId, refused);
      }
    } else {
      yield* c.loadContextPolicy();
      if (!c.canHandoff())
        return yield* c.notify.warning(
          "Select an available conversation policy to change agents. This also requires an updated app.",
        );
      const draft = c.drafts.snapshots[chatId];
      if (!draft) return yield* c.notify.warning("Continuing with another agent needs an updated app.");
      before = draft;
      version = composer.editVersion ?? 0;
      attempted = true;
      reconciled = false;
      // A started chat goes on with the other agent in a new chat beside
      // it, in its task (specs/tasks-and-splits/02); the original keeps its
      // agent, its session and its transcript.
      const result = yield* c.host.call("host/chats.handoff", { chatId, agentId, newChat: true });
      const next = result.chat;
      c.state.chats[next.id] = next;
      c.scheduler.receive(result.snapshot);
      // The host moved the prompt box's text to the new chat's draft and
      // cleared the original's: both composers show what the host keeps.
      c.drafts.apply(result.draft);
      c.drafts.apply(yield* c.drafts.read(chatId));
      reconciled = true;
      yield* loadOptions(c, next.id);
      yield* c.app.select(next.id, next.workspaceId);
      return;
    }
    yield* loadOptions(c, chatId);
  }).pipe(
    Effect.catch((error) =>
      Effect.gen(function* () {
        yield* c.notify.error(`Could not continue with this agent: ${errorMessage(error)}`);
        const sourceDraft = before;
        if (attempted && sourceDraft) {
          // Read-only reconciliation, never replay a handoff after an ambiguous
          // reply. Install its committed head before releasing deferred mutations.
          yield* Effect.gen(function* () {
            const [chats, , draft] = yield* Effect.all(
              [c.host.call("host/chats.list", {}), c.scheduler.read(chatId), c.drafts.read(chatId)],
              { concurrency: "unbounded" },
            );
            const selected = chats.chats.find((chat) => chat.id === chatId);
            if (selected) c.state.chats[chatId] = selected;
            yield* c.drafts.reconcileHandoff(sourceDraft, version, draft);
            reconciled = true;
            yield* loadOptions(c, chatId);
          }).pipe(
            Effect.catch((failure) =>
              c.notify.error(
                `Conversation state could not be refreshed; draft edits remain held: ${errorMessage(failure)}`,
              ),
            ),
          );
        }
      }),
    ),
    Effect.ensuring(
      Effect.sync(() => {
        composer.preparing = !reconciled;
        c.refresh(chatId);
      }),
    ),
  );
});
export const regenerateTranscripts = Effect.fn("Chat.regenerateTranscripts")(function* (c: Controller, chatId: string) {
  const composer = c.composer(chatId);
  if (composer.regenerating) return;
  composer.regenerating = true;
  c.refresh(chatId);
  yield* Effect.gen(function* () {
    const { artifacts } = yield* c.host.call("host/artifacts.list", { chatId });
    const failures: string[] = [];
    for (const artifact of artifacts) {
      const result = yield* Effect.result(
        c.host.call("host/artifacts.regenerate", { chatId, artifactId: artifact.id }),
      );
      if (result._tag === "Failure") failures.push(`${artifact.id}: ${errorMessage(result.failure)}`);
    }
    const message = artifacts.length
      ? `Regenerated ${artifacts.length - failures.length} of ${artifacts.length} transcript exports.`
      : "This chat has no transcript exports.";
    yield* failures.length ? c.notify.error(`${message} ${failures.join("; ")}`) : c.notify.info(message);
  }).pipe(
    Effect.catch((error) => c.notify.error(`Transcript regeneration failed: ${errorMessage(error)}`)),
    Effect.ensuring(
      Effect.sync(() => {
        composer.regenerating = false;
        c.refresh(chatId);
      }),
    ),
  );
});
export const moveDraft = Effect.fn("Chat.moveDraft")(function* (c: Controller, chat: Chat, workspaceId: string) {
  if (workspaceId === chat.workspaceId) return;
  yield* c.host.call("host/chats.update", { chatId: chat.id, workspaceId }).pipe(
    Effect.tap((moved) =>
      Effect.sync(() => {
        c.state.chats[moved.id] = moved;
      }),
    ),
    Effect.flatMap((moved) => c.app.select(moved.id, moved.workspaceId)),
    Effect.catch((error) => c.notify.error(`Could not move the chat: ${errorMessage(error)}`)),
  );
});

// A workspace's remove button in the workspace picker. Its chats go with it; the workspaces-changed event that follows
// redraws the picker.
export const removeWorkspace = Effect.fn("Chat.removeWorkspace")(function* (c: Controller, workspace: Workspace) {
  yield* c.host
    .call("host/workspaces.remove", { workspaceId: workspace.id })
    .pipe(Effect.catch((error) => c.notify.error(`Could not remove ${workspace.name}: ${errorMessage(error)}`)));
});

// The workspace picker's Add workspace folder…: the folder the user picks
// becomes a workspace, and the draft moves there.
export const moveDraftToNewWorkspace = Effect.fn("Chat.moveDraftToNewWorkspace")((c: Controller, chat: Chat) =>
  Effect.gen(function* () {
    const picked = yield* promise("pickFolder", () => c.api.pickFolder());
    if (!picked?.path) return;
    const workspace = yield* c.host.call("host/workspaces.add", { path: picked.path });
    yield* moveDraft(c, chat, workspace.id);
  }).pipe(Effect.catch((error) => c.notify.error(`Could not add the workspace: ${errorMessage(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.