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
Files
panes.ts12.4 KB
// Each chat has one pane view, kept while it is one of the last few
// shown so switching back is instant. Detail views (a subagent, a
// workflow) open in tabs through the divergence/tabs service.
import * as Scope from "effect/Scope";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import type { Chat, Element } from "divergence";
import type { Controller, ChatError, ChatView } from "./controller.ts";
import { registeredPane } from "./state.ts";
import type { Pane, PreparingPane } from "./state.ts";
import { paneReady, renderComposerView, renderPane } from "./views/panes.tsx";
import { findTask, nameOf, taskItems } from "./subagents.ts";
import { chatsOnScreen, presentationChats } from "./layout.ts";
import { unknownMethod } from "./scheduler.ts";
import { adoptSelected } from "./input-schema.ts";
import { centerPresentation, titlePresentation } from "./presentations.tsx";
import {
errorMessage,
loadChat,
loadOptions,
loadTranscript,
loadRequests,
noteRecent,
refreshHistory,
} from "./data.ts";
import type { TranscriptLoadOptions } from "./data.ts";
/** Chats whose panes stay mounted: ten total, or every visible pane when there are more. */
const RETAINED = 10;
function trimPanes(c: Controller) {
const visible = chatsOnScreen(c);
// A cold native selection resolves to the dynamic fallback, which keeps
// the pane it physically presents in `onScreen` until the replacement is
// ready. App state already names the requested chat, so pin both here.
if (c.state.onScreen) visible.add(c.state.onScreen);
if (c.state.newChat) visible.add(c.state.newChat);
const limit = Math.max(RETAINED, visible.size);
while (c.state.recentPanes.length > limit) {
let index = c.state.recentPanes.length - 1;
while (index >= 0 && visible.has(c.state.recentPanes[index]!)) index--;
if (index < 0) return;
const [old] = c.state.recentPanes.splice(index, 1);
if (old) removePane(c, old);
}
}
function retained(c: Controller, chatId: string): boolean {
return c.state.recentPanes.includes(chatId) || c.state.onScreen === chatId || chatsOnScreen(c).has(chatId);
}
export const ensureComposer = Effect.fn("Chat.ensureComposer")(function* (c: Controller, chatId: string) {
if (!c.state.composers[chatId]) {
c.composer(chatId);
if (c.state.restored) delete c.state.restored[chatId];
yield* Effect.forkIn(
c.drafts.load(chatId).pipe(Effect.catch((error) => c.notify.error(`Draft unavailable: ${error.message}`))),
c.scope,
{ startImmediately: true },
);
yield* Effect.forkIn(loadOptions(c, chatId), c.scope, { startImmediately: true });
}
});
export const ensureChat = Effect.fn("Chat.ensureChat")(function* (
c: Controller,
chatId: string,
options: TranscriptLoadOptions = { history: false },
) {
const kept = c.state.transcripts[chatId];
if (!kept || kept.carried) {
if (kept) kept.carried = false;
else c.transcript(chatId);
yield* Effect.forkIn(loadRequests(c, chatId), c.scope, { startImmediately: true });
}
const transcript = c.transcript(chatId);
if (transcript.snapshot.kind === "unread" && !transcript.loading)
yield* Effect.forkIn(loadTranscript(c, chatId, options), c.scope, { startImmediately: true });
});
const registerPane = Effect.fn("Chat.registerPane")(function* (
c: Controller,
chatId: string,
preparing: PreparingPane,
options: TranscriptLoadOptions,
) {
yield* ensureChat(c, chatId, options);
yield* ensureComposer(c, chatId);
const [view, composer, center, title] = yield* Effect.all(
[
c.views.add(`chat:${chatId}`, { slot: "pane", render: (ctx) => {
const tree = renderPane({ controller: c, ctx }, chatId);
const drawn = registeredPane(c.state.panes[chatId]);
const ready = paneReady(c, chatId);
if (drawn && (!drawn.drawn || drawn.ready !== ready)) {
drawn.drawn = true;
drawn.ready = ready;
c.presentations?.paneChanged(chatId);
}
return tree;
}, on: ["agents_changed"] }).pipe(Effect.provideService(Scope.Scope, c.scope)),
c.views.add(`composer:${chatId}`, { slot: "composer", render: (ctx) => renderComposerView({ controller: c, ctx }, chatId), on: ["agents_changed"] }).pipe(Effect.provideService(Scope.Scope, c.scope)),
centerPresentation(c, chatId).pipe(Effect.provideService(Scope.Scope, c.scope)),
titlePresentation(c, chatId).pipe(Effect.provideService(Scope.Scope, c.scope)),
] as const,
{ concurrency: "unbounded" },
);
const pane: Pane = { chatId, view, composer, centerPresentation: center, titlePresentation: title };
if (c.state.panes[chatId] === preparing) {
c.state.panes[chatId] = pane;
view.update();
c.presentations?.paneChanged(chatId);
if (!retained(c, chatId)) removePane(c, chatId);
} else {
view.remove();
composer.remove();
center.remove();
title.remove();
}
yield* Deferred.succeed(preparing.preparation, pane);
});
// The chat's pane view, made the first time it is selected or prepared ahead;
// the oldest beyond the retained few goes.
export const ensurePane = Effect.fn("Chat.ensurePane")(function* (
c: Controller,
chatId: string,
options: TranscriptLoadOptions = { history: false },
) {
c.state.recentPanes = [chatId, ...c.state.recentPanes.filter((id) => id !== chatId)];
trimPanes(c);
const entry = c.state.panes[chatId];
const pane = registeredPane(entry);
if (pane) {
yield* ensureChat(c, chatId, options);
if (!pane.stale) return pane;
pane.stale = false;
pane.view.update();
pane.composer?.update();
return pane;
}
if (entry && "preparation" in entry) return yield* Deferred.await(entry.preparation);
const preparing: PreparingPane = { chatId, preparation: Deferred.makeUnsafe<Pane>() };
c.state.panes[chatId] = preparing;
yield* Effect.forkIn(registerPane(c, chatId, preparing, options), c.scope, { startImmediately: true });
return yield* Deferred.await(preparing.preparation);
});
const finishPrehydration = Effect.fn("Chat.finishPrehydration")(function* (c: Controller, chatId: string) {
const transcript = c.state.transcripts[chatId];
if (transcript?.loading) yield* Deferred.await(transcript.loading);
const pane = registeredPane(c.state.panes[chatId]);
if (pane && retained(c, chatId) && (pane.stale || !pane.ready)) {
pane.stale = false;
pane.view.update();
pane.composer?.update();
} else if (!retained(c, chatId)) removePane(c, chatId);
});
/** Builds the fixed pane and presentation trees before selection, without the
* focus, recency, session preparation or history reconciliation of `followApp`. */
export const prehydratePresentation = Effect.fn("Chat.prehydratePresentation")(function* (c: Controller, chatId: string) {
if (!c.state.chats[chatId]) return;
const chats = [...presentationChats(c, chatId)];
yield* Effect.all(chats.map((id) => ensurePane(c, id, { history: false })), { concurrency: "unbounded" });
yield* Effect.all(chats.map((id) => finishPrehydration(c, id)), { concurrency: "unbounded" });
});
// A chat whose pane goes keeps no transcript here; the host keeps less of
// it too. It is read again, newest page first, when it shows.
export function removePane(c: Controller, chatId: string) {
const entry = c.state.panes[chatId];
const pane = registeredPane(entry);
c.state.recentPanes = c.state.recentPanes.filter((id) => id !== chatId);
// Registration owns its cleanup. Keeping the entry lets a selection adopt
// the same work instead of creating a second set of keyed views.
if (entry && !pane) return;
pane?.view.remove();
pane?.composer?.remove();
pane?.centerPresentation?.remove();
pane?.titlePresentation?.remove();
delete c.state.panes[chatId];
c.presentations?.remove(chatId);
if (c.api.app.state().chatId === chatId) return;
const transcript = c.state.transcripts[chatId];
if (transcript?.loading) return;
if (transcript) {
for (const item of transcript.items) delete c.state.itemImages[item.id];
delete c.state.transcripts[chatId];
}
if (!pane && !transcript) return;
// An older host has no `chats.close`: it keeps everything, as before.
Effect.runFork(c.host.call("host/chats.close", { chatId }).pipe(Effect.catch(() => Effect.void)));
}
// A host without the method is an older one: nothing to prepare. A failed
// preparation arrives as `prepareError` and is toasted; any other failure is toasted here.
const prepareChat = (c: Controller, chatId: string) =>
c.host
.call("host/chats.prepare", { chatId })
.pipe(
Effect.catch((error) =>
unknownMethod(error)
? Effect.void
: c.notify.error(`Preparing the conversation failed: ${errorMessage(error)}`),
),
);
export const followApp = Effect.fn("Chat.followApp")(function* (c: Controller): Effect.fn.Return<void, ChatError> {
let app = c.api.app.state();
if (app.route !== "chat" || !app.chatId) {
c.state.shownChat = null;
return;
}
if (!adoptSelected(c.state.chats, app)) {
yield* loadChat(c, app.chatId);
app = c.api.app.state();
if (app.route !== "chat" || !app.chatId) {
c.state.shownChat = null;
return;
}
}
const chat = c.state.chats[app.chatId];
if (!chat) return;
const retryFailed = c.state.transcripts[chat.id]?.snapshot.kind === "failed";
yield* ensurePane(c, chat.id);
const current = c.api.app.state();
if (current.route !== "chat" || current.chatId !== chat.id) return;
if (chat.id !== c.state.shownChat) {
c.state.shownChat = chat.id;
yield* Effect.forkIn(noteRecent(c, chat.id), c.scope, { startImmediately: true });
yield* Effect.forkIn(prepareChat(c, chat.id), c.scope, { startImmediately: true });
// A retained failure retries on a new show, never on a render of that show.
if (retryFailed && !c.transcript(chat.id).loading)
yield* Effect.forkIn(loadTranscript(c, chat.id, { history: false }), c.scope, { startImmediately: true });
yield* Effect.forkIn(refreshHistory(c, chat.id), c.scope, { startImmediately: true });
}
if (chat.id !== c.state.promptedChat && !c.state.switcher) {
c.state.promptedChat = chat.id;
yield* c.views.focus(`prompt-${chat.id}`);
}
});
/** A subagent's or a workflow's tab: one of the chat plugin's own tab kinds, opened with its
* chat, so it shows with that chat's task (specs/tasks-and-splits/03 and 08). */
const showInPane = Effect.fn("Chat.showInPane")(function* (c: Controller, chat: Chat, kind: "subagent" | "workflow", taskId: string) {
yield* Effect.tryPromise(() => c.api.layouts.open({ kind, key: taskId, chatId: chat.id })).pipe(
Effect.catch((error) => c.notify.error(`Could not open the tab: ${errorMessage(error)}`)),
);
});
/** A subagent's or a workflow's tab title, from whichever transcript holds it. */
export function taskTabTitle(c: Controller, taskId: string, fallback: string): string {
for (const transcript of Object.values(c.state.transcripts)) {
const item = findTask(taskItems(transcript), taskId);
if (item) return item.task.workflow ? item.task.name || item.task.title || fallback : item.task.title || nameOf(item.task);
}
return fallback;
}
export const openWorkflow = Effect.fn("Chat.openWorkflow")(function* (c: Controller, chat: Chat, taskId: string) {
yield* showInPane(c, chat, "workflow", taskId);
});
export const openSubagent = Effect.fn("Chat.openSubagent")(function* (
c: Controller,
chat: Chat,
taskId: string,
): Effect.fn.Return<void, ChatError> {
const item = findTask(taskItems(c.transcript(chat.id)), taskId);
if (item?.task.workflow) return yield* openWorkflow(c, chat, taskId);
// A reconcile leaves a settled subagent's transcript unread; the tab reads it.
if (item && item.task.kind !== "terminal" && !item.items?.length) {
const reads = c.state.taskReads;
reads.set(taskId, null);
yield* Effect.forkIn(
c.host.call("host/chats.load_task", { chatId: chat.id, taskId }).pipe(
// The read ends in `transcript_reset`, and the chat reads its rows again.
Effect.tap(() =>
Effect.gen(function* () {
const transcript = c.transcript(chat.id);
while (transcript.loading) yield* Deferred.await(transcript.loading);
reads.delete(taskId);
}),
),
Effect.catch((error) =>
Effect.sync(() => reads.set(taskId, `Could not read the subagent's transcript: ${errorMessage(error)}`)),
),
Effect.ensuring(Effect.sync(() => c.refreshSubagentTabs(chat.id))),
),
c.scope,
{ startImmediately: true },
);
}
yield* showInPane(c, chat, "subagent", taskId);
});Versions
| Version | Published | Plugin API | Size | Permissions | Status |
|---|---|---|---|---|---|
| 0.2.9latest | Nov 21, 2026 | >=5 <6 | 349 KB | 5 permissions | Listed |
| 0.2.8 | Nov 16, 2026 | >=5 <6 | 348.6 KB | 5 permissions | Listed |
| 0.2.7 | Nov 11, 2026 | >=5 <6 | 314.3 KB | 5 permissions | Listed |
| 0.2.6 | Nov 9, 2026 | >=5 <6 | 306.2 KB | 5 permissions | Listed |
| 0.2.5 | Oct 27, 2026 | >=2 <4 | 178.6 KB | 5 permissions | Listed |
No comments yet.