Official
sidebar
Built-in sidebar 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/sidebar@0.2.4
Permissions in 0.2.4
Files
sections.ts35 KB
// The sidebar's pure model: the chats the list holds, their status and the
// section it puts them in, titles and matches. Functions take the state they
// read; nothing here starts work.
import type { EffectClient } from "divergence/effect";
import type * as Fiber from "effect/Fiber";
import type { AgentInfo, Chat, ChatStatus, HostEvents, PresetColor, TaskStatus, Workspace } from "divergence";
import type { Layout, Task } from "divergence/protocol";
import type { Chat as ChatService } from "../chat/contract.ts";
import { createPreview, updatePreview } from "./preview.ts";
import type { Preview } from "./preview.ts";
import { relativeTime } from "../sdk/ui/time.ts";
import { chatStatus as classifyStatus } from "../sdk/ui/status.ts";
import { fuzzy } from "../sdk/ui/fuzzy.ts";
/** A chat's status as the sidebar shows it: blocked > running > review > idle. */
export type ChatRowStatus = "blocked" | "running" | "failed" | "review" | "idle";
export type SectionId = "drafts" | "pinned" | "queued" | "needs-you" | "running" | "finished" | "open" | "settled";
export interface Section {
readonly id: SectionId;
readonly label: string;
readonly tone: string;
readonly chats: Chat[];
}
/** What the status rules need from a chat. */
export interface ChatLike {
readonly id: string;
readonly status: ChatStatus;
readonly sessionId?: string;
readonly working?: { readonly agents: number; readonly commands: number };
}
/**
* Where the user put a chat: its sort key in that section, kept while the
* chat stays there. Pinned is a placement of its own; `chosen` marks a chat
* the user moved between Open and Finished, which stays where they put it
* until its state changes.
*/
export interface Placement {
readonly section: SectionId;
readonly rank: number;
readonly chosen?: boolean;
}
/** A place in the list: in `section`, before the chat `before` (null: at its end). */
export interface Spot {
readonly section: SectionId;
readonly before: string | null;
}
/**
* A chat being dragged: where it came from and where it would land now.
* `settling` while the sections the drag showed above it have just pushed
* the list down under the pointer: the first row the pointer is then over
* is where the list moved, not where the user moved.
*/
export interface Dragging {
readonly id: string;
readonly from: Spot;
to: Spot;
settling: boolean;
}
/** What the pointer of a drag is over: a chat's row (and which half), a section's heading, or the list as a whole (`inside` false once it left). */
export type Over =
| { readonly row: string; readonly zone: string }
| { readonly heading: SectionId }
| { readonly inside: boolean };
export interface Editing {
id: string;
title: string;
/** Set when the row being renamed is a task row: the name is the task's. */
task?: string;
}
export interface SidebarState {
workspaces: Workspace[];
/// The preset colours a workspace's folder can take (from the host).
colors: readonly PresetColor[];
chats: Chat[];
agents: AgentInfo[];
filter: string[]; // the chosen workspace ids; none means all
query: string;
lastAgent: string | null;
editing: Editing | null;
showAll: Partial<Record<SectionId, boolean>>;
collapsed: Partial<Record<SectionId, boolean>>; // sections folded to their heading; kept in plugin storage
placed: Record<string, Placement>; // chat id -> where the user put it; kept in plugin storage
dragging: Dragging | null; // the chat being dragged in the list, while it is
queued: ReadonlySet<string>; // chats the chat plugin queued (its service)
draftTitles: Record<string, string>; // chat id -> title from the prompt being typed
starting: ReadonlySet<string>; // chats whose sent prompt starts a run the host has not reported yet
submitting: Set<string>;
finished: Record<string, number>; // chat id -> when its run ended, this session
previews: Record<string, Preview>; // latest model activity, hydrated only for visible chats
subagents: Record<string, Map<string, TaskStatus | undefined>>; // chat id -> subagent id -> status
// The rows' tasks the host keeps (specs/tasks-and-splits/01): each chat's
// task by chat id, and the tasks whose chats the user chose to list
// under their row (plugin storage `expandedTasks`).
tasks: Record<string, Task>;
homes: Record<string, string>;
expanded: Set<string>;
// The task whose chats the popover beside its row lists, while it shows.
popover: string | null;
// The popover closing: it fades out until its time is up.
popoverClosing: boolean;
// The row a carried chat would join, its middle third under the pointer (document 4).
joining: string | null;
// The row whose menu is open (a child row's when `child`), with the plugins' entries once they come.
rowMenu: { chatId: string; child: boolean; entries: readonly { id: string; title: string }[] } | null;
// The rows just archived, which the notice at the foot of the list offers back for a few seconds.
undo: ArchivedRow[];
loaded: boolean;
// The divergence/chat client while its provider runs, and the fiber
// following its queue and draft titles.
chat: EffectClient<typeof ChatService> | undefined;
follow: Fiber.Fiber<void> | undefined;
}
export function initialState(): SidebarState {
return {
workspaces: [],
colors: [],
chats: [],
agents: [],
filter: [],
query: "",
lastAgent: null,
editing: null,
showAll: {},
collapsed: {},
placed: {},
dragging: null,
queued: new Set(),
draftTitles: {},
starting: new Set(),
submitting: new Set(),
finished: {},
previews: {},
subagents: {},
tasks: {},
homes: {},
expanded: new Set(),
popover: null,
popoverClosing: false,
joining: null,
rowMenu: null,
undo: [],
loaded: false,
chat: undefined,
follow: undefined,
};
}
// Drafts and Complete are paged; the rest show everything. Complete, pinned
// at the foot of the list until it is shown whole, shows a shorter page.
export const PAGE = 5;
export const RETAINED_SECTIONS: readonly SectionId[] = ["drafts", "settled"];
export const COMPLETE_PAGE = 3;
/** How many rows a paged section shows before "Show more". */
export const pageOf = (id: SectionId) => (id === "settled" ? COMPLETE_PAGE : PAGE);
/** Plugin storage key of the folded sections. */
export const COLLAPSED_KEY = "collapsedSections";
/** Plugin storage key of where the user dragged chats. */
export const PLACED_KEY = "placedChats";
/** Plugin storage key of the tasks whose chats the user listed under their row. */
export const EXPANDED_KEY = "expandedTasks";
// --- tasks ---------------------------------------------------------------------
/** The chat ids of a layout in its order: the top-left pane first, each pane's tabs in order. */
function chatIdsOf(layout: Layout): string[] {
if (layout.kind === "split") return layout.children.flatMap((child) => chatIdsOf(child.layout));
return layout.tabs.flatMap((tab) => (tab.kind === "chat" ? [tab.chatId] : []));
}
/** Records a task the host sent, and the task of each of its chats. */
export function noteTask(state: SidebarState, task: Task): void {
const before = state.tasks[task.id];
if (before) for (const id of chatIdsOf(before.layout.root)) if (state.homes[id] === task.id) delete state.homes[id];
state.tasks[task.id] = task;
for (const id of chatIdsOf(task.layout.root)) state.homes[id] = task.id;
}
export function forgetTask(state: SidebarState, taskId: string): void {
const task = state.tasks[taskId];
if (!task) return;
for (const id of chatIdsOf(task.layout.root)) if (state.homes[id] === taskId) delete state.homes[id];
delete state.tasks[taskId];
state.expanded.delete(taskId);
}
export function taskOf(state: SidebarState, chatId: string): Task | undefined {
const home = state.homes[chatId];
return home ? state.tasks[home] : undefined;
}
/** A task's chats the list knows, in layout order. */
export function taskChats(state: SidebarState, task: Task): Chat[] {
const byId = new Map(state.chats.map((chat) => [chat.id, chat]));
return chatIdsOf(task.layout.root).flatMap((id) => {
const chat = byId.get(id);
return chat && !chat.archived ? [chat] : [];
});
}
/** Whether a chat's row is a task row: its task holds two or more chats (document 1). */
export function isTaskRow(state: SidebarState, chat: Pick<Chat, "id">): boolean {
const task = taskOf(state, chat.id);
return !!task && taskChats(state, task).length > 1;
}
/** Whether a chat stands for its row: the first chat of its task, or one whose task the list has not heard of yet. */
export function leadsRow(state: SidebarState, chat: Pick<Chat, "id">): boolean {
const task = taskOf(state, chat.id);
return !task || taskChats(state, task)[0]?.id === chat.id;
}
/** Checks a row off, or opens it again, here at once; the host is told separately. */
export function setCompleted(state: SidebarState, chatId: string, completed: boolean): void {
const task = taskOf(state, chatId);
if (task) state.tasks[task.id] = { ...task, completedAt: completed ? new Date().toISOString() : null };
}
/** The chat a row opens on: its task's focused pane's active chat, so a task opens as it was left. */
export function openingChat(state: SidebarState, chat: Chat): Chat {
const task = taskOf(state, chat.id);
if (!task) return chat;
const focused = (function find(layout: Layout): string | null {
if (layout.kind === "pane")
return layout.id === task.layout.focused && layout.active.kind === "chat" ? layout.active.chatId : null;
for (const child of layout.children) {
const found = find(child.layout);
if (found) return found;
}
return null;
})(task.layout.root);
return (focused && state.chats.find((c) => c.id === focused && !c.archived)) || chat;
}
/** When a row was checked off: its task's, which belongs to the row and not to each chat. */
export function completedOf(state: SidebarState, chat: Pick<Chat, "id">): string | undefined {
return taskOf(state, chat.id)?.completedAt ?? undefined;
}
export const SECTIONS: ReadonlyArray<{ id: SectionId; label: string; tone: string }> = [
{ id: "drafts", label: "Drafts", tone: "muted" },
{ id: "pinned", label: "Pinned", tone: "muted" },
{ id: "queued", label: "Queued", tone: "info" },
{ id: "needs-you", label: "Needs you", tone: "warning" },
{ id: "running", label: "Running", tone: "info" },
{ id: "finished", label: "Finished", tone: "muted" },
{ id: "open", label: "Open", tone: "muted" },
{ id: "settled", label: "Complete", tone: "muted" },
];
// The subagents and background commands of the chat that still work, after
// the chat's own turn too. The host counts them; an older host does not, and
// then the subagents this sidebar saw start stand in (no commands).
export function stillWorking(state: SidebarState, chat: ChatLike): { agents: number; commands: number } {
if (chat.working) return chat.working;
let agents = 0;
for (const status of state.subagents[chat.id]?.values() ?? []) if (status === "running" || status === "waiting") agents++;
return { agents, commands: 0 };
}
const isWorking = (working: { agents: number; commands: number }) => working.agents + working.commands > 0;
// blocked > running > failed (its last turn) > review (finished this session) > idle
export function chatStatus(state: SidebarState, chat: ChatLike): ChatRowStatus {
const status = classifyStatus(chat.status);
if (status === "blocked") return "blocked";
if (isWorking(stillWorking(state, chat))) return "running";
return turnStatus(state, chat);
}
// The status of the chat's agent and the subagents it started, leaving out the background commands still at work after its turn: a chat whose agent is done shows in Finished or Open while its commands run, with the spinner as its mark.
function agentStatus(state: SidebarState, chat: ChatLike): ChatRowStatus {
const status = classifyStatus(chat.status);
if (status === "blocked") return "blocked";
if (stillWorking(state, chat).agents > 0) return "running";
return turnStatus(state, chat);
}
function turnStatus(state: SidebarState, chat: ChatLike): ChatRowStatus {
const status = classifyStatus(chat.status);
if (status === "running" || state.starting.has(chat.id)) return "running";
if (status === "failed") return "failed";
if (state.finished[chat.id]) return "review";
return "idle";
}
// A chat nobody has prompted yet. The chat plugin reports it starting the
// moment its first prompt is sent; the session comes seconds later.
export function isDraft(state: SidebarState, chat: ChatLike): boolean {
return !chat.sessionId && chat.status === "idle" && !state.queued.has(chat.id) && !state.starting.has(chat.id);
}
// The section a row's chats put it in, before the user's choices: a task
// row takes the most urgent of its chats' sections (document 1), and is a
// draft only when every chat in it is one.
const URGENCY: readonly SectionId[] = ["needs-you", "running", "queued", "finished", "open", "drafts"];
function liveSection(state: SidebarState, chat: ChatLike): SectionId {
const task = taskOf(state, chat.id);
const chats = task ? taskChats(state, task) : [];
if (chats.length < 2) return chatSection(state, chat);
const sections = new Set(chats.map((member) => chatSection(state, member)));
return URGENCY.find((section) => sections.has(section)) ?? "open";
}
/** A row's status mark: a task row's sums up its chats', the most urgent first. */
const STATUS_URGENCY: readonly ChatRowStatus[] = ["blocked", "running", "failed", "review", "idle"];
export function rowStatus(state: SidebarState, chat: ChatLike): ChatRowStatus {
const task = taskOf(state, chat.id);
const chats = task ? taskChats(state, task) : [];
if (chats.length < 2) return chatStatus(state, chat);
const statuses = new Set(chats.map((member) => chatStatus(state, member)));
return STATUS_URGENCY.find((status) => statuses.has(status)) ?? "idle";
}
// The section a chat's own state puts it in.
function chatSection(state: SidebarState, chat: ChatLike): SectionId {
if (isDraft(state, chat)) return "drafts";
if (state.queued.has(chat.id)) return "queued";
const status = agentStatus(state, chat);
if (status === "blocked") return "needs-you";
if (status === "running") return "running";
if (status === "review" || status === "failed") return "finished";
return "open";
}
const idle = (section: SectionId) => section === "open" || section === "finished";
// The section a chat shows in. A checked-off chat is in Complete at once;
// a pinned one stays in Pinned whatever it does; one the user moved between
// Open and Finished stays there while it is in either.
export function sectionOf(state: SidebarState, chat: ChatLike): SectionId {
if (completedOf(state, chat)) return "settled";
const live = liveSection(state, chat);
if (live === "drafts" || live === "queued") return live;
const placed = state.placed[chat.id];
if (placed?.section === "pinned") return "pinned";
if (placed?.chosen && idle(live) && idle(placed.section)) return placed.section;
return live;
}
/** The sections a chat can be dragged to: its own; Pinned and Complete; and the section its state puts it in, or for an idle chat both Open and Finished. A draft stays among the drafts. */
export function dropTargets(state: SidebarState, chat: Chat): ReadonlySet<SectionId> {
const live = liveSection(state, chat);
const own = sectionOf(state, chat);
// The queue keeps its own order.
if (live === "queued") return new Set();
if (live === "drafts") return new Set([own, live]);
return new Set<SectionId>([own, "pinned", "settled", ...(idle(live) ? (["open", "finished"] as const) : [live])]);
}
// A draft shows the title its prompt will give it as the user types.
export function chatTitleOf(state: SidebarState, chat: Chat): string {
return state.draftTitles[chat.id] ?? chat.title;
}
/** A row's title: a task row's own name, or its first chat's title (document 1). */
export function rowTitleOf(state: SidebarState, chat: Chat): string {
const task = taskOf(state, chat.id);
return (task && isTaskRow(state, chat) && task.title) || chatTitleOf(state, chat);
}
// The search's scores by title, for the query they were taken for: one
// draw asks for the same chats many times, and each title is matched once.
let scored = { query: "", byTitle: new Map<string, number | null>() };
/** How well a chat's title matches the search, fuzzily (higher is better), or null when it does not; 0 while there is no search. */
export function searchScore(state: SidebarState, chat: Chat): number | null {
const query = state.query.trim();
if (!query) return 0;
if (scored.query !== query) scored = { query, byTitle: new Map() };
const title = chatTitleOf(state, chat);
let score = scored.byTitle.get(title);
if (score === undefined) {
score = fuzzy(query, title)?.score ?? null;
scored.byTitle.set(title, score);
}
return score;
}
export function matches(state: SidebarState, chat: Chat): boolean {
return searchScore(state, chat) !== null;
}
/** The chats of a row the search matches: a task row matches by its name or by any of its chats (document 1, Search). */
export function rowMatches(state: SidebarState, chat: Chat): Chat[] {
const task = taskOf(state, chat.id);
const chats = task ? taskChats(state, task) : [chat];
if (chats.length < 2) return matches(state, chat) ? [chat] : [];
const named = task?.title && state.query.trim() && fuzzy(state.query.trim(), task.title);
const matched = chats.filter((member) => matches(state, member));
return named ? chats : matched;
}
/** The rows the list shows, each by the chat that leads it: of the chosen workspaces, not archived, matching the search, the most recently active first. */
export function visibleChats(state: SidebarState): Chat[] {
return state.chats
.filter(
(c) =>
!c.archived &&
leadsRow(state, c) &&
(!state.filter.length || state.filter.includes(c.workspaceId)) &&
rowMatches(state, c).length > 0,
)
.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0));
}
/** A chat's sort key in a section, the largest first: where the user dragged it, else when it was checked off (Complete), finished (Finished) or last active (the rest). */
export function sortKey(state: SidebarState, chat: Chat, section: SectionId): number {
const placed = state.placed[chat.id];
if (placed?.section === section) return placed.rank;
if (section === "settled") return Date.parse(completedOf(state, chat) ?? "") || 0;
if (section === "finished") return state.finished[chat.id] ?? 0;
return Date.parse(chat.updatedAt) || 0;
}
// A section's chats in its order: the best matches of a search first, then
// by `sortKey`, the largest first.
function ordered(state: SidebarState, id: SectionId, members: Chat[]): Chat[] {
return members.sort(
(a, b) => searchScore(state, b)! - searchScore(state, a)! || sortKey(state, b, id) - sortKey(state, a, id),
);
}
/** The visible chats by section, in section order; empty sections left out. While a chat is dragged it shows where it would land, and the sections it could land in show even when empty. */
export function sections(state: SidebarState): Section[] {
return grouped(state, state.dragging);
}
function grouped(state: SidebarState, drag: Dragging | null): Section[] {
const chats = visibleChats(state);
const moving = drag ? chats.find((c) => c.id === drag.id) : undefined;
const targets = moving ? dropTargets(state, moving) : undefined;
const out: Section[] = [];
for (const section of SECTIONS) {
const members = ordered(
state,
section.id,
chats.filter((c) => c !== moving && sectionOf(state, c) === section.id),
);
if (moving && drag!.to.section === section.id) {
const at = members.findIndex((c) => c.id === drag!.to.before);
members.splice(at < 0 ? members.length : at, 0, moving);
}
if (!members.length && !targets?.has(section.id)) continue;
out.push({ ...section, chats: members });
}
return out;
}
/** Whether a chat's row can be dragged: not a queued one, whose order is the queue's. */
export const canPlace = (section: SectionId): boolean => section !== "queued";
// Where a chat is in the list now: its section and the chat after it.
function spotOf(state: SidebarState, id: string): Spot | null {
for (const section of sections(state)) {
const at = section.chats.findIndex((c) => c.id === id);
if (at >= 0) return { section: section.id, before: section.chats[at + 1]?.id ?? null };
}
return null;
}
// The chats of a section as the list shows them, the dragged one left out.
function others(state: SidebarState, section: SectionId, id: string): Chat[] {
return sections(state).find((s) => s.id === section)?.chats.filter((c) => c.id !== id) ?? [];
}
// Starts dragging `id` unless it is already dragged.
function begin(state: SidebarState, id: string): Dragging | null {
if (state.dragging?.id === id) return state.dragging;
const from = spotOf(state, id);
if (!from) return null;
const shown = new Set(sections(state).map((s) => s.id));
state.dragging = { id, from, to: from, settling: false };
const above = SECTIONS.findIndex((s) => s.id === from.section);
state.dragging.settling = sections(state).some(
(s) => !shown.has(s.id) && SECTIONS.findIndex((t) => t.id === s.id) < above,
);
return state.dragging;
}
// Where in the list the pointer puts the dragged chat: beside the row it
// is over, on the side of the half it is in, at the top of the section
// whose heading it is over, or back where it came from once it left the
// list. Null where it would not move it.
function spotAt(state: SidebarState, drag: Dragging, over: Over): Spot | null {
if ("inside" in over) return over.inside ? null : drag.from;
if ("heading" in over) return { section: over.heading, before: others(state, over.heading, drag.id)[0]?.id ?? null };
if (over.row === drag.id) return null;
const target = state.chats.find((c) => c.id === over.row);
if (!target) return null;
const section = sectionOf(state, target);
const rest = others(state, section, drag.id);
const at = rest.findIndex((c) => c.id === over.row);
if (at < 0) return null;
// An older kernel without `reorder` reports `into`: the chat takes the other's place.
return { section, before: rest[over.zone === "after" ? at + 1 : at]?.id ?? null };
}
// Moves the dragged chat's place to `to` when it may land there. Returns
// whether it moved.
function moveTo(state: SidebarState, drag: Dragging, to: Spot | null): boolean {
const chat = state.chats.find((c) => c.id === drag.id);
if (!to || !chat || !dropTargets(state, chat).has(to.section)) return false;
if (to.section === drag.to.section && to.before === drag.to.before) return false;
drag.to = to;
return true;
}
/**
* Moves the place of the dragged chat `id` to where the pointer is (the
* first word of a drag starts it, and the sections it may land in show),
* when the chat may go to that section. Returns whether the list changed.
*/
export function dragOver(state: SidebarState, id: string, over: Over): boolean {
const starts = state.dragging?.id !== id;
const drag = begin(state, id);
if (!drag) return false;
if (drag.settling && !("inside" in over) && !("row" in over && over.row === id)) {
drag.settling = false;
return starts;
}
return moveTo(state, drag, spotAt(state, drag, over)) || starts;
}
/** What a drop asks of the host beyond the list: checking the chat off (`true`) or opening it again (`false`). */
export interface Dropped {
readonly completed?: boolean;
}
/**
* Lands the dragged chat `id` where its place is now, and ends the drag; an
* older kernel that tells only the drop gives where it landed (`over`). The
* section it lands in decides its state: Pinned pins it, Complete checks it
* off, Open or Finished keep it there while it stays idle, and leaving
* Complete opens it again. Every chat of that section then keeps the order
* the drop left it in, until it leaves the section. Returns null when the
* drag landed nowhere new.
*/
export function dropDragged(state: SidebarState, id: string, over?: Over): Dropped | null {
const drag = begin(state, id);
state.dragging = null;
if (!drag) return null;
if (over) moveTo(state, drag, spotAt(state, { ...drag, settling: false }, over));
const { to } = drag;
const index = state.chats.findIndex((c) => c.id === id);
const chat = state.chats[index];
if (!chat || (to.section === drag.from.section && to.before === drag.from.before)) return null;
const from = sectionOf(state, chat);
if (!dropTargets(state, chat).has(to.section)) return null;
const completed = to.section === "settled" ? true : from === "settled" ? false : undefined;
if (completed !== undefined) setCompleted(state, id, completed);
// Moved to Open, a finished chat has been seen.
if (to.section === "open") delete state.finished[id];
const live = liveSection(state, state.chats[index]!);
const chosen = idle(to.section) && to.section !== live;
// Every other chat of the section, the ones the list does not show too,
// in the section's order, with the dropped one in its place.
const moved = state.chats[index]!;
const members = ordered(
state,
to.section,
state.chats.filter((c) => c.id !== id && !c.archived && leadsRow(state, c) && sectionOf(state, c) === to.section),
);
const at = members.findIndex((c) => c.id === to.before);
members.splice(at < 0 ? members.length : at, 0, moved);
const top = Date.now();
members.forEach((member, n) => {
const keep = member.id === id ? chosen : state.placed[member.id]?.chosen;
state.placed[member.id] = { section: to.section, rank: top - n, ...(keep ? { chosen: true } : {}) };
});
return { completed };
}
/** Ends a drag that landed nowhere: the chat goes back where it was. Returns whether a drag was on. */
export function endDrag(state: SidebarState): boolean {
const was = !!state.dragging;
state.dragging = null;
return was;
}
/** Pins a chat at the top of Pinned, or unpins it back into the section its state puts it in. */
export function togglePinned(state: SidebarState, chat: Chat): void {
if (sectionOf(state, chat) === "pinned") {
delete state.placed[chat.id];
return;
}
const ranks = Object.values(state.placed).flatMap((p) => (p.section === "pinned" ? [p.rank] : []));
state.placed[chat.id] = { section: "pinned", rank: Math.max(Date.now(), ...ranks.map((rank) => rank + 1)) };
}
/** Forgets where the user put chats that have since left that section or the list. A pin goes only with the chat's check or archive: a chat that shows among the drafts for a moment keeps it. Returns whether any were forgotten. */
export function prunePlaced(state: SidebarState): boolean {
let pruned = false;
for (const [id, placed] of Object.entries(state.placed)) {
const chat = state.chats.find((c) => c.id === id);
const kept = placed.section === "pinned" ? !!chat && !completedOf(state, chat) : chat && sectionOf(state, chat) === placed.section;
if (chat && !chat.archived && kept) continue;
delete state.placed[id];
pruned = true;
}
return pruned;
}
/** A section's rows as the list shows them: none while it is folded (but the place of a chat dragged into it), a page of a paged section until "Show more". A search shows its matches in folded sections too, and pages them like the rest, its best matches first. */
export function shownChats(state: SidebarState, section: Section): Chat[] {
if (state.collapsed[section.id] && !state.query) return section.chats.filter((c) => c.id === state.dragging?.id);
const all = !!state.showAll[section.id] || !RETAINED_SECTIONS.includes(section.id);
return all ? section.chats : section.chats.slice(0, pageOf(section.id));
}
/** Every chat row the list shows, top to bottom: what Cmd+1 to Cmd+9 open. */
export function listedChats(state: SidebarState): Chat[] {
return sections(state).flatMap((section) => shownChats(state, section));
}
/** The chat Cmd+W moves to: the open chat (any section but Complete) below this one in the list, else the one above. Folded and paged rows count; a chat being dragged counts where it was. */
export function nextOpenChat(state: SidebarState, chatId: string): Chat | undefined {
const open = grouped(state, null)
.filter((section) => section.id !== "settled")
.flatMap((section) => section.chats);
const index = open.findIndex((c) => c.id === chatId);
if (index < 0) return open[0];
return open[index + 1] ?? open[index - 1];
}
/// The agent the user worked with most recently in this workspace: what
/// the composer switched a chat to counts, not only what New chat used.
export function recentAgent(state: SidebarState, workspaceId: string): string | undefined {
const enabled = new Set(state.agents.map((a) => a.id));
return state.chats
.filter((c) => c.workspaceId === workspaceId && !c.archived && enabled.has(c.agentId))
.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1))[0]?.agentId;
}
export function elapsed(now: number, iso: string): string {
return relativeTime(iso, "elapsed", now);
}
// --- archiving and undo ------------------------------------------------------
/**
* A row archived from the list, as Undo brings it back: its chats (the one
* that leads it first), its name, whether it was checked off, and where it
* was in its section. A chat archived out of a task of several (`from`)
* goes back to its tab's place in that task instead.
*/
export interface ArchivedRow {
readonly title: string;
readonly chatIds: readonly string[];
/** The name of its task, which the host forgets once the task holds one chat. */
readonly name: string | null;
readonly completed: boolean;
readonly queued: boolean;
/** Where it was in its section; none for a queued chat, whose place is the queue's, or a chat of a task. */
readonly placed: Placement | null;
readonly from: { readonly taskId: string; readonly paneId: string; readonly index: number } | null;
}
/** The pane and the index in it of a chat's tab. */
function tabPlace(layout: Layout, chatId: string): { paneId: string; index: number } | null {
if (layout.kind === "split") {
for (const child of layout.children) {
const found = tabPlace(child.layout, chatId);
if (found) return found;
}
return null;
}
const index = layout.tabs.findIndex((tab) => tab.kind === "chat" && tab.chatId === chatId);
return index < 0 ? null : { paneId: layout.id, index };
}
/** Whether a layout still has the pane `paneId`. */
export function hasPane(layout: Layout, paneId: string): boolean {
return layout.kind === "pane" ? layout.id === paneId : layout.children.some((child) => hasPane(child.layout, paneId));
}
/** The row that `lead` leads, as archiving it takes it out of the list: every chat of its task. */
export function archivedRow(state: SidebarState, lead: Chat): ArchivedRow {
const task = taskOf(state, lead.id);
const chats = task ? taskChats(state, task) : [lead];
const section = sectionOf(state, lead);
const own = state.placed[lead.id];
return {
title: rowTitleOf(state, lead),
chatIds: chats.map((chat) => chat.id),
name: chats.length > 1 ? (task?.title ?? null) : null,
completed: !!completedOf(state, lead),
queued: section === "queued",
placed: section === "queued" ? null : own?.section === section ? own : { section, rank: sortKey(state, lead, section) },
from: null,
};
}
/** A chat archived out of a task of several, which keeps its row: its tab's place in the task. */
export function archivedChild(state: SidebarState, chat: Chat): ArchivedRow {
const task = taskOf(state, chat.id)!;
return {
title: chatTitleOf(state, chat),
chatIds: [chat.id],
name: task.title ?? null,
completed: false,
queued: false,
placed: null,
from: { taskId: task.id, ...tabPlace(task.layout.root, chat.id)! },
};
}
/** What the notice says: the row's title for one row, else how many chats went. */
export function undoLabel(rows: readonly ArchivedRow[]): string {
if (rows.length === 1) return `Archived “${rows[0]!.title}”`;
return `Archived ${rows.reduce((n, row) => n + row.chatIds.length, 0)} chats`;
}
/** Whether a row brought back is in the list as it was: its chats back in one task, checked off as they were. */
export function isBack(state: SidebarState, row: ArchivedRow): boolean {
const task = taskOf(state, row.chatIds[0]!);
return !!task && taskChats(state, task).length === row.chatIds.length && !!task.completedAt === row.completed;
}
// --- event mutators ----------------------------------------------------------
// These keep the controller's state current between renders. They mutate
// the state object in place.
export function applyChatChange(state: SidebarState, chat: Chat): void {
const index = state.chats.findIndex((c) => c.id === chat.id);
if (index >= 0) state.chats[index] = chat;
else state.chats.unshift(chat);
}
export function applyChatRemoved(state: SidebarState, chatId: string): void {
state.chats = state.chats.filter((chat) => chat.id !== chatId);
delete state.previews[chatId];
}
export function applyTranscriptReset(state: SidebarState, chatId: string): void {
delete state.previews[chatId];
}
/** Applies an agent event; returns whether the sidebar must redraw. */
export function applyAgentEvent(state: SidebarState, event: HostEvents["agent"]): boolean {
const { chatId, taskId, kind } = event;
if (kind.event === "task") {
// Only an older host needs these: a newer one counts the chat's work on the chat itself.
const tasks = (state.subagents[chatId] ??= new Map());
const live = (status: TaskStatus | undefined) => status === "running" || status === "waiting";
const before = live(tasks.get(kind.id));
if (kind.kind === "terminal") tasks.delete(kind.id);
else tasks.set(kind.id, kind.status);
return live(tasks.get(kind.id)) !== before;
}
// A subagent's words are not the chat's latest line.
if (taskId) return false;
const preview = (state.previews[chatId] ??= createPreview());
const changed = updatePreview(preview, kind);
if (kind.event === "run_finished") state.finished[chatId] = Date.now();
return changed || kind.event === "run_finished";
}
/// A workspace's mark: its project icon, else the icon the app gives it
/// (the Divergence logo on the Plugins workspace), else a folder in its colour; the coloured folder
/// too when the user chose it over the icon.
export function workspaceMarkOf(w: Workspace | undefined): { image?: string; icon?: string; color?: PresetColor } {
if (!w) return { icon: "folder" };
if (w.icon && !w.useColor) return { image: w.icon };
if (w.mark && !w.useColor) return { icon: w.mark };
return w.color ? { icon: "folder-solid", color: w.color } : { icon: "folder" };
}
/// What a workspace's mark can be, for a picker: its project icon (or the
/// app's mark), when it has one, then the folder in each preset colour;
/// `value` is the one shown now.
export function workspaceLooks(w: Workspace, colors: readonly PresetColor[]) {
const own = w.icon ? { image: w.icon } : w.mark ? { icon: w.mark } : null;
const value = own && !w.useColor ? "icon" : (w.color ?? "");
const name = (color: string) => color.charAt(0).toUpperCase() + color.slice(1);
return {
value,
options: [
...(own ? [{ value: "icon", label: w.icon ? "Project icon" : "App icon", ...own }] : []),
...colors.map((color) => ({ value: color, label: name(color), icon: "folder-solid", color })),
],
};
}
No comments yet.