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 convergence/chat@0.2.4
Permissions in 0.2.4
Files
composer.ts31 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, Skill, SubmitEvent } from "convergence";
import type { Prompt } from "./state.ts";
import type { Controller, ChatError } from "./controller.ts";
import type { MentionTag, Mention } from "./mentions.ts";
import { acceptMention as withMention, findTags, keepSegments, matchMentions, removeTag } from "./mentions.ts";
import { amendedInput, blocksFor, compositionFor, inputId, steeringReason } from "./composition.ts";
import { announceQueued, errorMessage, loadOptions, persistQueues, syncDraftTitle, textChanged } from "./data.ts";
const IMAGE_FILE = /\.(png|jpe?g|gif|webp|bmp|tiff?|ico|svg)$/i;
export const onChange = Effect.fn("Chat.onChange")(function* (c: Controller, chatId: string, text: string) {
const composer = c.composer(chatId),
mentions = c.api.mentions.list();
const kept = keepSegments(composer.text, text, mentions),
tagsBefore = findTags(composer.text, mentions).length;
composer.text = kept;
c.refreshComposer(chatId);
yield* textChanged(c, chatId);
if (kept !== text || findTags(kept, mentions).length !== tagsBefore) {
if (composer.picker) composer.picker = null;
c.refreshComposer(chatId);
if (kept !== text) return;
}
text = kept;
if (text.startsWith("/") && !/\s/.test(text)) {
composer.picker = { kind: "commands", query: text.slice(1) };
c.refreshComposer(chatId);
return;
}
if (text.startsWith("$") && !/\s/.test(text)) {
composer.picker = { kind: "skills", query: text.slice(1) };
c.refreshComposer(chatId);
return;
}
const last = text.split(/\s/).pop() ?? "";
if (last.startsWith("@")) {
const query = last.slice(1);
composer.picker = { kind: "files", query };
const chat = c.state.chats[chatId];
if (chat)
yield* Effect.forkIn(
c.host.call("host/fs.search", { workspaceId: chat.workspaceId, query, limit: 12 }).pipe(
Effect.tap((result) =>
Effect.sync(() => {
if (composer.picker?.kind === "files" && composer.picker.query === query) {
composer.files = result.paths;
c.refreshComposer(chatId);
}
}),
),
),
c.scope,
{ startImmediately: true },
);
c.refreshComposer(chatId);
return;
}
if (composer.picker) {
composer.picker = null;
c.refreshComposer(chatId);
}
});
export const acceptSkill = Effect.fn("Chat.acceptSkill")(function* (c: Controller, chatId: string, skill: Skill) {
const composer = c.composer(chatId);
composer.text = `$${skill.name} `;
composer.picker = null;
yield* textChanged(c, chatId);
c.refreshComposer(chatId);
});
export const acceptFile = Effect.fn("Chat.acceptFile")(function* (c: Controller, chatId: string, path: string) {
const composer = c.composer(chatId),
at = composer.text.lastIndexOf("@");
composer.text = `${at >= 0 ? composer.text.slice(0, at) : composer.text}@${path} `;
composer.picker = null;
yield* textChanged(c, chatId);
c.refreshComposer(chatId);
});
export const acceptMention = Effect.fn("Chat.acceptMention")(function* (
c: Controller,
chatId: string,
mention: Mention,
) {
const composer = c.composer(chatId);
composer.text = withMention(composer.text, mention);
composer.picker = null;
yield* textChanged(c, chatId);
c.refreshComposer(chatId);
});
// A reply to part of a message: the part as a quote after what is typed,
// with an empty line above it and 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" : "\n"}${quoted}\n`;
}
export const quote = Effect.fn("Chat.quote")(function* (c: Controller, chatId: string, text: string) {
const composer = c.composer(chatId);
composer.text = withQuote(composer.text, text);
yield* textChanged(c, chatId);
c.refreshComposer(chatId);
yield* c.views.focus(`prompt-${chatId}`);
});
export const dropTag = Effect.fn("Chat.dropTag")(function* (c: Controller, chatId: string, tag: MentionTag) {
const composer = c.composer(chatId);
composer.text = removeTag(composer.text, tag);
yield* textChanged(c, chatId);
c.view.update();
});
export const acceptCommand = Effect.fn("Chat.acceptCommand")(function* (
c: Controller,
chatId: string,
command: { name: string; inputHint?: string | null },
run = true,
) {
const composer = c.composer(chatId);
composer.text = `/${command.name} `;
composer.picker = null;
yield* textChanged(c, chatId);
if (run && !command.inputHint) yield* Effect.forkIn(send(c, chatId), c.scope, { startImmediately: true });
else c.refreshComposer(chatId);
});
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 separator = composer.text && !composer.text.endsWith(" ") ? " " : "";
composer.text = `${composer.text}${separator}${mentions.map((path) => `@${path}`).join(" ")} `;
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.picker = null;
else if (key === "up" || key === "down") {
const count =
picker.kind === "files"
? matchMentions(c.api.mentions.list(), picker.query).length + composer.files.length
: picker.kind === "commands"
? c.matchingCommands(composer, picker.query).length
: c.matchingSkills(composer, picker.query).length;
if (count) picker.index = ((picker.index ?? 0) + (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.matchingCommands(composer, "").some((command) => composer.text.trim() === `/${command.name}`)
)
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);
});
/// Accepts the picker's highlighted entry; false when there is none. Enter
/// runs a command that takes no input, Tab (`run` false) only completes it.
export const acceptPicked = Effect.fn("Chat.acceptPicked")(function* (c: Controller, chatId: string, run = true) {
const composer = c.composer(chatId),
selected = composer.picker?.index ?? 0;
if (composer.picker?.kind === "files") {
const mentions = matchMentions(c.api.mentions.list(), composer.picker.query),
mention = mentions[selected],
file = composer.files[selected - mentions.length];
if (mention) yield* acceptMention(c, chatId, mention);
else if (file) yield* acceptFile(c, chatId, file);
return !!(mention || file);
}
if (composer.picker?.kind === "commands") {
const command = c.matchingCommands(composer, composer.picker.query)[selected];
if (command) yield* acceptCommand(c, chatId, command, run);
return !!command;
}
if (composer.picker?.kind === "skills") {
const skill = c.matchingSkills(composer, composer.picker.query)[selected];
if (skill) yield* acceptSkill(c, chatId, skill);
return !!skill;
}
return false;
});
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 what Enter asked for once the chat is ready; nothing when the
/// chat went away or the user cleared the prompt meanwhile.
const sendWhenReady = Effect.fn("Chat.sendWhenReady")(function* (c: Controller, chatId: string) {
const composer = c.composer(chatId);
while (c.state.chats[chatId] && composer.sendWhenReady !== undefined && !readyToSend(c, chatId))
yield* Effect.sleep(SEND_WHEN_READY_POLL);
const queue = composer.sendWhenReady;
composer.sendWhenReady = undefined;
c.refresh(chatId);
if (queue !== undefined && c.state.chats[chatId]) yield* submitComposition(c, chatId, queue);
});
const SEND_WHEN_READY_POLL = "100 millis";
export const submitComposition = Effect.fn("Chat.submitComposition")(function* (
c: Controller,
chatId: string,
queue: boolean,
): Effect.fn.Return<void, ChatError> {
const composer = c.composer(chatId),
chat = c.state.chats[chatId];
if (!chat || composer.submitting) return;
// The chat is not ready to send yet (the host is resuming its session
// after a relaunch, its options load): the prompt waits and goes when it
// is, instead of the key doing nothing.
if (!readyToSend(c, chatId)) {
if (composer.sendWhenReady === undefined && (composer.text.trim() || composer.attachments.length)) {
composer.sendWhenReady = queue;
c.refresh(chatId);
yield* Effect.forkIn(sendWhenReady(c, chatId), c.scope, { startImmediately: true });
}
return;
}
const text = composer.text.trim(),
originalText = composer.text,
attachments = [...composer.attachments],
carriedBlocks = [...(composer.carriedBlocks ?? [])];
if (!text && !attachments.length && !carriedBlocks.length) return;
const reason = !queue && steeringReason(c, chat);
if (reason) 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;
composer.error = undefined;
composer.text = "";
composer.attachments = [];
composer.carriedBlocks = [];
composer.picker = null;
let acknowledged = false;
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;
// 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)}`;
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* () {
composer.outgoing = undefined;
composer.submitting = 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 "convergence/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 failed send leaves the draft and its error in place; the queue
// moves on. A sent one holds it until the host reports it running.
if (!composer.error) return;
c.state.releasing = null;
}
});
export const setOption = Effect.fn("Chat.setOption")(function* (
c: Controller,
chatId: string,
optionId: string,
value: string,
) {
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("convergence").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 });
} 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 snapshot = yield* c.scheduler.read(chatId);
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;
const result = yield* c.host.call("host/chats.handoff", {
chatId,
agentId,
revision: snapshot.revision,
draftRevision: draft.revision,
});
c.state.chats[chatId] = result.chat;
c.scheduler.receive(result.snapshot);
yield* c.drafts.reconcileHandoff(draft, version, result.draft);
reconciled = true;
}
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)}`)),
);
});Versions
| Version | Published | Plugin API | Size | Permissions | Status |
|---|---|---|---|---|---|
| 0.2.5latest | Nov 21, 2026 | >=2 <4 | 174.6 KB | 5 permissions | Listed |
| 0.2.4 | Oct 25, 2026 | >=2 <4 | 174.2 KB | 5 permissions | Listed |
| 0.2.3 | Oct 24, 2026 | >=2 <4 | 165.4 KB | 5 permissions | Listed |
| 0.2.2 | Oct 23, 2026 | >=2 <4 | 165 KB | 5 permissions | Listed |
| 0.2.1 | Oct 6, 2026 | >=2 <3 | 111.8 KB | 5 permissions | Listed |
| 0.2.0 | Oct 5, 2026 | >=2 <3 | 105.1 KB | 5 permissions | Listed |
No comments yet.