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.6
Permissions in 0.2.6
Files
sections.ts50.1 KB
// The sidebar's pure model: the chats the list holds, their status and the
// section it puts them in, and titles. 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, COMMANDS_HOLD_FOR_MS } from "../sdk/ui/status.ts";
import { ALERT, CHECK, CIRCLE_CHECK, CLOCK, INBOX, MOON, PENCIL, PIN } from "../sdk/ui/icons.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" | "snoozed" | "settled";
export interface Section {
readonly id: SectionId;
readonly label: string;
/** The mark after its label, as SVG; none for Running, whose heading spins instead. */
readonly mark: string | null;
readonly chats: Chat[];
/** Whether it is docked at the foot of the list. */
readonly docked: boolean;
}
/**
* The order of the sections, top to bottom: the ones in the list, then the
* ones docked at its foot. Every section is in exactly one of the two.
*/
export interface Arrangement {
readonly list: readonly SectionId[];
readonly dock: readonly SectionId[];
}
/** A section being dragged by its heading, and the order it would leave if dropped now. */
export interface MovingSection {
readonly id: SectionId;
to: Arrangement;
}
/** Where the pointer of a section's drag is: beside a section (its heading's half, or after it for its rows), at the end of the list or the dock while it shows none, or over the sidebar (`inside` false once it left). */
export type SectionOver =
| { readonly section: SectionId; readonly zone: "before" | "after" }
| { readonly area: "list" | "dock" }
| { readonly inside: boolean };
/** 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 };
readonly updatedAt?: string;
}
/** How long a chat stays in Finished after its run ends before it moves to Open. */
export const FINISHED_FOR_MS = 60 * 60 * 1000;
// When a chat's last run ended: the stamp its `run_finished` left this session, else, for a chat whose last turn failed, its last activity, which the host keeps across restarts.
function finishedAt(state: SidebarState, chat: ChatLike): number | undefined {
const stamp = state.finished[chat.id];
if (stamp !== undefined) return stamp;
return classifyStatus(chat.status) === "failed" && chat.updatedAt ? Date.parse(chat.updatedAt) : undefined;
}
// Whether a chat finished its run within the last FINISHED_FOR_MS.
function recentlyFinished(state: SidebarState, chat: ChatLike, now = Date.now()): boolean {
const at = finishedAt(state, chat);
return at !== undefined && now - at < FINISHED_FOR_MS;
}
// Whether a chat whose agent is done stays in Running: its background commands still run and its run ended within the last COMMANDS_HOLD_FOR_MS.
function heldRunning(state: SidebarState, chat: ChatLike, now = Date.now()): boolean {
const at = finishedAt(state, chat);
return at !== undefined && now - at < COMMANDS_HOLD_FOR_MS && stillWorking(state, chat).commands > 0;
}
/** The next moment time alone moves a chat of the list: out of Running when its commands' minute is up, from Finished to Open, or out of Snoozed when its snooze ends, if one will. */
export function nextTimedMove(state: SidebarState, now = Date.now()): number | undefined {
let next: number | undefined;
for (const placed of Object.values(state.placed))
if (placed.section === "snoozed" && placed.until !== undefined && placed.until > now) next = Math.min(next ?? Infinity, placed.until);
for (const chat of state.chats) {
const at = finishedAt(state, chat);
if (at === undefined || chat.archived || now - at >= FINISHED_FOR_MS) continue;
const due = heldRunning(state, chat, now) ? at + COMMANDS_HOLD_FOR_MS : at + FINISHED_FOR_MS;
next = Math.min(next ?? Infinity, due);
}
return next;
}
/**
* Where the user put a chat: its sort key in that section, kept while the
* chat stays there. Pinned and Snoozed are placements of their own, and a
* snooze with `until` (epoch milliseconds) ends then, while one without it
* lasts until the user ends it; `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;
readonly until?: number;
}
/** 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.
* The docked sections float over the foot of the list, and the rows under
* them still hear the pointer: `onDock` while the pointer is over the dock,
* when only what the dock's rows and headings last said (`said.dock`)
* counts, and what the list's said (`said.list`) waits until it leaves.
*/
export interface Dragging {
readonly id: string;
readonly from: Spot;
to: Spot;
onDock: boolean;
said: { list?: Over; dock?: Over };
}
/** The part of the list a row or heading is in: the list, or the dock that floats over its foot. */
export type Part = "list" | "dock";
/** 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;
/** The title the field opened with: Enter on it unchanged writes nothing, so a row that follows its first chat's title keeps following it. */
seed: 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: readonly Chat[]; // replaced on every change, never edited, so `chatById` can index each list once
agents: AgentInfo[];
filter: string[]; // the chosen workspace ids; none means all
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
dockHeight: number | null; // the height the user dragged the docked sections' rows to, null for five rows each; kept in plugin storage
// The dock's edge being dragged: the rows' height when it was pressed, and the pointer's first place over the sidebar once it moves.
resizingDock: { from: number; anchor: number | null } | null;
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
arrangement: Arrangement; // the order of the sections and which are docked; kept in plugin storage
movingSection: MovingSection | null; // the section being dragged by its heading, 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
sent: Record<string, number>; // chat id -> when the chat plugin last reported it starting a run, this session
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`), where in the row it was right-clicked
// (none when its command opened it), and the plugins' entries once they come.
rowMenu: { chatId: string; child: boolean; at: { x: number; y: number } | null; 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[];
// The chats Close Chat put away, the last first, which Reopen Closed Chat (Cmd+Shift+T) brings
// back: an archived one with the row it left, a checked-off one with none.
closed: { chatId: string; row: ArchivedRow | null }[];
// The workspace whose Remove was clicked once: the next click removes it.
removing: string | null;
// The route the Options menu was opened on, while it is open: a change of route closes it.
options: string | null;
// The keys bound to the row menu's commands, by command id, as last read.
keys: Record<string, string>;
loaded: boolean;
// Why the first read of the lists failed, shown in place of the list until one succeeds.
failed: string | null;
// 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: [],
lastAgent: null,
editing: null,
showAll: {},
// Snoozed and Complete start folded: Complete's heading alone takes the sidebar's last row.
collapsed: { ...DEFAULT_COLLAPSED },
dockHeight: null,
resizingDock: null,
placed: {},
dragging: null,
arrangement: DEFAULT_ARRANGEMENT,
movingSection: null,
queued: new Set(),
draftTitles: {},
starting: new Set(),
sent: {},
submitting: new Set(),
finished: {},
previews: {},
subagents: {},
tasks: {},
homes: {},
expanded: new Set(),
popover: null,
popoverClosing: false,
joining: null,
rowMenu: null,
undo: [],
closed: [],
removing: null,
options: null,
keys: {},
loaded: false,
failed: null,
chat: undefined,
follow: undefined,
};
}
// Drafts and Complete are paged in the list; the rest show everything. A
// docked section's rows scroll in a box five rows tall (`DOCK_ROWS`), and it
// sends at most `DOCK_PAGE` of them before "Show more", so a long Complete
// never lays out every chat it holds.
export const PAGE = 5;
export const RETAINED_SECTIONS: readonly SectionId[] = ["drafts", "settled"];
export const DOCK_ROWS = 5;
export const DOCK_PAGE = 50;
/** How many rows a paged section shows before "Show more". */
export const pageOf = (section: Pick<Section, "id" | "docked">) => (section.docked ? DOCK_PAGE : PAGE);
/**
* The height each docked section's rows get once the user dragged the dock
* to `total`: an even share each, where a section whose rows need less than
* its share keeps only what they need and leaves the rest to the others.
* `needs` are the full heights of the sections' rows.
*/
export function shareDock(total: number, needs: readonly number[]): number[] {
const shares = needs.map(() => 0);
let left = total;
const order = needs.map((_, index) => index).sort((a, b) => needs[a]! - needs[b]!);
order.forEach((index, at) => {
shares[index] = Math.min(needs[index]!, left / (order.length - at));
left -= shares[index]!;
});
return shares;
}
/** 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 order of the sections and which are docked. */
export const ARRANGEMENT_KEY = "sectionOrder";
/** Plugin storage key of the tasks whose chats the user listed under their row. */
export const EXPANDED_KEY = "expandedTasks";
/** Plugin storage key of the height the user dragged the docked sections' rows to. */
export const DOCK_HEIGHT_KEY = "dockHeight";
// --- 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;
}
// The chats of each list the state held, by id: built once per list, since
// every change replaces the list. Drawing asks for a row's task chats once or
// more per row, and rebuilding this for each made a draw grow with the square
// of the chats.
const indexes = new WeakMap<readonly Chat[], ReadonlyMap<string, Chat>>();
export function chatById(state: SidebarState): ReadonlyMap<string, Chat> {
let index = indexes.get(state.chats);
if (!index) indexes.set(state.chats, (index = new Map(state.chats.map((chat) => [chat.id, chat]))));
return index;
}
/** A task's chats the list knows, in layout order. */
export function taskChats(state: SidebarState, task: Task): Chat[] {
const byId = chatById(state);
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;
}
/** The chat that stands for a row, by the task id a row menu command gets: its task's first chat, or the chat of that id when no task has it. */
export function rowOfTask(state: SidebarState, taskId: string): Chat | undefined {
const task = state.tasks[taskId];
return task ? taskChats(state, task)[0] : chatById(state).get(taskId);
}
/** 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; mark: string | null }> = [
{ id: "drafts", label: "Drafts", mark: PENCIL },
{ id: "pinned", label: "Pinned", mark: PIN },
{ id: "queued", label: "Queued", mark: CLOCK },
{ id: "needs-you", label: "Needs you", mark: ALERT },
{ id: "finished", label: "Finished", mark: CHECK },
{ id: "open", label: "Open", mark: INBOX },
{ id: "running", label: "Running", mark: null },
{ id: "snoozed", label: "Snoozed", mark: MOON },
{ id: "settled", label: "Complete", mark: CIRCLE_CHECK },
];
/** Running, Snoozed and Complete start docked at the foot of the list, the rest in it. */
export const DEFAULT_ARRANGEMENT: Arrangement = {
list: ["drafts", "pinned", "queued", "needs-you", "finished", "open"],
dock: ["running", "snoozed", "settled"],
};
/** The sections folded until the user folds or unfolds them. */
export const DEFAULT_COLLAPSED: Readonly<Partial<Record<SectionId, boolean>>> = { snoozed: true, settled: true };
/** A saved folded set made whole: a section it does not name (one added since) takes its default. An array, as older versions saved it, names the folded sections and knows only the sections before Snoozed. */
export function collapsedFrom(saved: readonly string[] | Readonly<Record<string, boolean>>): Partial<Record<SectionId, boolean>> {
const known = (id: SectionId) => (Array.isArray(saved) ? id !== "snoozed" : id in saved);
const folded = (id: SectionId) => (Array.isArray(saved) ? saved.includes(id) : (saved as Record<string, boolean>)[id]);
return Object.fromEntries(
SECTIONS.flatMap(({ id }) => ((known(id) ? folded(id) : DEFAULT_COLLAPSED[id]) ? [[id, true]] : [])),
);
}
/** A saved order made whole: unknown and repeated sections left out, and a section it lacks (one added since) right after the section it follows in its default part, wherever that one is now, or at the end of the list when it leads its default part. */
export function arrangementFrom(saved: { list: readonly string[]; dock: readonly string[] }): Arrangement {
const seen = new Set<string>();
const keep = (ids: readonly string[]) =>
ids.filter((id): id is SectionId => SECTIONS.some((s) => s.id === id) && !seen.has(id) && !!seen.add(id));
const list = keep(saved.list);
const dock = keep(saved.dock);
for (const defaults of [DEFAULT_ARRANGEMENT.list, DEFAULT_ARRANGEMENT.dock])
defaults.forEach((id, index) => {
if (seen.has(id)) return;
const after = defaults[index - 1];
const part = after === undefined ? list : dock.includes(after) ? dock : list;
part.splice(after === undefined || !part.includes(after) ? part.length : part.indexOf(after) + 1, 0, id);
seen.add(id);
});
return { list, dock };
}
/** The order the list shows: the one a section's drag would leave, while one is dragged. */
export const arrangementOf = (state: SidebarState): Arrangement => state.movingSection?.to ?? state.arrangement;
const sameArrangement = (a: Arrangement, b: Arrangement) =>
a.list.join() === b.list.join() && a.dock.join() === b.dock.join();
/** `from` with section `id` moved beside another (into that one's part), or to the end of the list or the dock. */
export function moveSection(from: Arrangement, id: SectionId, to: Exclude<SectionOver, { inside: boolean }>): Arrangement {
const list = from.list.filter((s) => s !== id);
const dock = from.dock.filter((s) => s !== id);
if ("area" in to) return to.area === "dock" ? { list, dock: [...dock, id] } : { list: [...list, id], dock };
const part = list.includes(to.section) ? list : dock;
part.splice(part.indexOf(to.section) + (to.zone === "after" ? 1 : 0), 0, id);
return { list, dock };
}
/**
* Moves the section `id` being dragged to where the pointer is (the first
* word of its drag starts it). Over its own heading it stays; a pointer that
* left the sidebar takes it back where it was. Returns whether the list
* changed.
*/
export function dragSection(state: SidebarState, id: SectionId, over: SectionOver): boolean {
const starts = state.movingSection?.id !== id;
if (starts) state.movingSection = { id, to: state.arrangement };
const moving = state.movingSection!;
if ("inside" in over && over.inside) return starts;
if ("section" in over && over.section === id) return starts;
const to = "inside" in over ? state.arrangement : moveSection(moving.to, id, over);
if (sameArrangement(to, moving.to)) return starts;
moving.to = to;
return true;
}
/** Lands the dragged section where its place is now and ends its drag. Returns whether the order changed. */
export function dropSection(state: SidebarState, id: SectionId): boolean {
const moving = state.movingSection;
state.movingSection = null;
if (moving?.id !== id || sameArrangement(moving.to, state.arrangement)) return false;
state.arrangement = moving.to;
return true;
}
// 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 };
}
// The status of the chat's agent and the subagents it started:
// blocked > running > failed (its last turn) > review (finished in the last hour) > idle.
// Background commands still at work after the turn leave it out: the spinner is for an agent at work.
export function chatStatus(state: SidebarState, chat: ChatLike): ChatRowStatus {
const status = classifyStatus(chat.status);
if (status === "blocked") return "blocked";
if (status === "running" || state.starting.has(chat.id) || stillWorking(state, chat).agents > 0) return "running";
if (status === "failed") return "failed";
if (recentlyFinished(state, chat)) 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 = chatStatus(state, chat);
if (status === "blocked") return "needs-you";
if (status === "running" || heldRunning(state, chat)) return "running";
if (status === "review" || (status === "failed" && recentlyFinished(state, chat))) return "finished";
return "open";
}
const idle = (section: SectionId) => section === "open" || section === "finished";
/** Whether a chat is snoozed now: until its snooze's time, or until the user ends one without a time. */
export function isSnoozed(state: SidebarState, chat: Pick<ChatLike, "id">, now = Date.now()): boolean {
const placed = state.placed[chat.id];
return placed?.section === "snoozed" && (placed.until === undefined || placed.until > now);
}
// The section a chat shows in. A checked-off chat is in Complete at once;
// a snoozed one stays in Snoozed until its time and a pinned one 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";
if (isSnoozed(state, chat)) return "snoozed";
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, Snoozed 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", "snoozed", "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 rows the list shows, each by the chat that leads it: of the chosen workspaces, not archived, 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)))
.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). A sent prompt makes a chat active as it is sent, so it takes its place before the host reports it. */
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 finishedAt(state, chat) ?? 0;
return Math.max(Date.parse(chat.updatedAt) || 0, state.sent[chat.id] ?? 0);
}
/** Where the row of a chat stands: the section and the sort key of each chat of its row. An event that changes it moves the row. */
export function standing(state: SidebarState, chatId: string): string {
const task = taskOf(state, chatId);
const own = chatById(state).get(chatId);
const chats = task ? taskChats(state, task) : own ? [own] : [];
return chats
.map((chat) => {
const section = sectionOf(state, chat);
return `${chat.id}:${section}:${sortKey(state, chat, section)}`;
})
.join("|");
}
// A section's chats in its order: by `sortKey`, the largest first.
function ordered(state: SidebarState, id: SectionId, members: Chat[]): Chat[] {
return members.sort((a, b) => 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, unless showing one would move the dragged row under the pointer (`showsEmpty`). */
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[] = [];
const { list, dock } = arrangementOf(state);
const order = [...list.map((id) => ({ id, docked: false })), ...dock.map((id) => ({ id, docked: true }))];
const source = moving ? order.findIndex((s) => s.id === drag!.from.section) : -1;
// Each chat's section once, not once for every section.
const bySection = new Map<SectionId, Chat[]>();
for (const chat of chats) {
if (chat === moving) continue;
const id = sectionOf(state, chat);
const members = bySection.get(id);
if (members) members.push(chat);
else bySection.set(id, [chat]);
}
for (const [index, { id, docked }] of order.entries()) {
const section = { ...SECTIONS.find((s) => s.id === id)!, docked };
const members = ordered(state, section.id, bySection.get(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) && showsEmpty(order, source, index))) continue;
out.push({ ...section, chats: members });
}
return out;
}
// Whether a section the dragged chat may land in shows while empty. A
// section appearing above the dragged row in the list, or below it in the
// dock (which grows up from the foot), would move the row and every row
// near it under a pointer that did not move, so those stay hidden: an
// empty Pinned takes a chat by its Pin button instead. Its own section
// always shows, so the place it left stays where it was.
function showsEmpty(order: ReadonlyArray<{ id: SectionId; docked: boolean }>, source: number, index: number): boolean {
if (index === source) return true;
const from = order[source];
if (!from) return false;
if (from.docked) return !order[index]!.docked || index < source;
return order[index]!.docked || index > source;
}
/** 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;
state.dragging = { id, from, to: from, onDock: false, said: {} };
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`. Over a section it may not land
// in, its place goes back where it came from, so a release there changes
// nothing rather than landing it where it last was. Returns whether it
// moved.
function moveTo(state: SidebarState, drag: Dragging, spot: Spot | null): boolean {
const chat = state.chats.find((c) => c.id === drag.id);
if (!spot || !chat) return false;
const to = dropTargets(state, chat).has(spot.section) ? spot : drag.from;
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).
* A row or heading says which part of the list it is in (`part`): while
* the pointer is over the dock, the rows of the list under it are not
* heard. Returns whether the list changed.
*/
export function dragOver(state: SidebarState, id: string, over: Over, part: Part = "list"): boolean {
const starts = state.dragging?.id !== id;
const drag = begin(state, id);
if (!drag) return false;
if (!("inside" in over)) {
drag.said[part] = over;
if (drag.onDock && part === "list") return starts;
}
return moveTo(state, drag, spotAt(state, drag, over)) || starts;
}
/** The pointer of the drag of `id` came onto the dock (`on`) or left it: what that part's rows last said counts now. Returns whether the list changed. */
export function dragOnDock(state: SidebarState, id: string, on: boolean): boolean {
const starts = state.dragging?.id !== id;
const drag = begin(state, id);
if (!drag || drag.onDock === on) return !!drag && starts;
drag.onDock = on;
const said = drag.said[on ? "dock" : "list"];
return (!!said && moveTo(state, drag, spotAt(state, drag, said))) || 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, Snoozed snoozes it
* until the user ends it (one already snoozed keeps its time), 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, 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 own order, with the dropped one in its place.
const moved = state.chats[index]!;
const members = state.chats
.filter((c) => c.id !== id && !c.archived && leadsRow(state, c) && sectionOf(state, c) === to.section)
.sort((a, b) => sortKey(state, b, to.section) - sortKey(state, a, 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 own = state.placed[member.id];
const keep = member.id === id ? chosen : own?.chosen;
const until = to.section === "snoozed" && own?.section === "snoozed" ? own.until : undefined;
state.placed[member.id] = { section: to.section, rank: top - n, ...(keep ? { chosen: true } : {}), ...(until !== undefined ? { until } : {}) };
});
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)) };
}
/** Snoozes a row until `until` (epoch milliseconds), or until the user ends it when null, at the top of Snoozed; a pin it had goes. */
export function snooze(state: SidebarState, chat: Pick<Chat, "id">, until: number | null): void {
const ranks = Object.values(state.placed).flatMap((p) => (p.section === "snoozed" ? [p.rank] : []));
const rank = Math.max(Date.now(), ...ranks.map((r) => r + 1));
state.placed[chat.id] = { section: "snoozed", rank, ...(until === null ? {} : { until }) };
}
/** Ends a row's snooze: it goes back to the section its state puts it in. */
export function unsnooze(state: SidebarState, chat: Pick<Chat, "id">): void {
if (state.placed[chat.id]?.section === "snoozed") delete state.placed[chat.id];
}
/** Forgets where the user put chats that have since left that section or the list. A pin or a snooze goes only with the chat's check or archive: a chat that shows among the drafts for a moment keeps it. A snooze whose time is up puts an idle chat at the top of Open, where it stays until its state changes, and leaves a working one where its state puts it. Returns whether any changed. */
export function prunePlaced(state: SidebarState, now = Date.now()): boolean {
let pruned = false;
for (const [id, placed] of Object.entries(state.placed)) {
const chat = state.chats.find((c) => c.id === id);
if (placed.section === "snoozed" && placed.until !== undefined && placed.until <= now && chat && !chat.archived && !completedOf(state, chat)) {
if (idle(liveSection(state, chat))) state.placed[id] = { section: "open", rank: placed.until, chosen: true };
else delete state.placed[id];
pruned = true;
continue;
}
const kept = placed.section === "pinned" || placed.section === "snoozed" ? !!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: while it is folded, only the row of the chat on screen (`focused`, from `focusedRows`) and the place of a chat dragged into it; none while it is carried by its heading; a page of a paged section until "Show more". */
export function shownChats(state: SidebarState, section: Section, focused: string | null = null): Chat[] {
// A section carried by its heading is its heading alone.
if (state.movingSection?.id === section.id) return [];
if (state.collapsed[section.id]) return section.chats.filter((c) => c.id === focused || c.id === state.dragging?.id);
const all = !!state.showAll[section.id] || !(section.docked || RETAINED_SECTIONS.includes(section.id));
// A page grows to keep the place of a chat dragged past its end in view.
const dragged = section.chats.findIndex((c) => c.id === state.dragging?.id);
return all ? section.chats : section.chats.slice(0, Math.max(pageOf(section), dragged + 1));
}
/** The row each chat of a folded section stands under, by chat id: its own row, or for a chat of a task its task's row. The chat on screen picks its row out of this, so a folded section shows that one row under its heading. */
export function focusedRows(state: SidebarState, all: readonly Section[]): Record<string, string> {
const rows: Record<string, string> = {};
for (const section of all) {
if (!state.collapsed[section.id]) continue;
for (const chat of section.chats) {
const task = isTaskRow(state, chat) ? taskOf(state, chat.id) : undefined;
for (const member of task ? taskChats(state, task) : [chat]) rows[member.id] = chat.id;
}
}
return rows;
}
/** Every chat row the list shows, top to bottom: what Cmd+1 to Cmd+9 open. A folded section's row of the chat on screen is not one of them, so the numbers stay put as the user moves between chats. */
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;
}
/** How many chats Close Chat remembers for Reopen Closed Chat. */
const CLOSED_KEPT = 20;
/** Notes a chat Close Chat put away, the last first; `row` is the row it left when it was archived. */
export function rememberClosed(state: SidebarState, chatId: string, row: ArchivedRow | null): void {
state.closed = [{ chatId, row }, ...state.closed.filter((closed) => closed.chatId !== chatId)].slice(0, CLOSED_KEPT);
}
/** 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);
state.chats = index >= 0 ? state.chats.map((c, i) => (i === index ? chat : c)) : [chat, ...state.chats];
}
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";
}
/// 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.