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.7
Permissions in 0.2.7
Files
controller.ts36.2 KB
// Sidebar actions: the refresh that loads workspaces and chats, the chat
// writes (new, rename; archiving is archive.ts), and the lazy transcript
// hydration the rows trigger. One layer owns the state.
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import * as z from "zod";
import { App, Host, Kernel, Notify, Plugin, Services, hostError, parse, promise } from "divergence/effect";
import type { EffectClient, HostError } from "divergence/effect";
import type { Chat as ChatService } from "../chat/contract.ts";
import type { Api, Chat, HostEvents, PresetColor, ViewHandle, Workspace } from "divergence";
import type { Over, Part, SectionId, SectionOver, SidebarState } from "./sections.ts";
import { restingReads } from "./rest.ts";
import type { Task } from "divergence/protocol";
import {
ARRANGEMENT_KEY,
COLLAPSED_KEY,
DOCK_HEIGHT_KEY,
EXPANDED_KEY,
PLACED_KEY,
SECTIONS,
applyAgentEvent,
nextTimedMove,
applyChatChange,
applyChatRemoved,
applyTranscriptReset,
arrangementFrom,
collapsedFrom,
dragOver,
dragOnDock,
dragSection,
dropDragged,
dropSection,
endDrag,
initialState,
listedChats,
nextOpenChat,
prunePlaced,
sectionOf,
standing,
togglePinned,
snooze,
unsnooze,
completedOf,
forgetTask,
isTaskRow,
leadsRow,
noteTask,
openingChat,
rememberClosed,
setCompleted,
taskOf,
} from "./sections.ts";
import { makePeek } from "./peek.ts";
import { chatsInUse, makeNextChat, newChatAgent, newChatWorkspace } from "./next-chat.ts";
import { makeRename } from "./rename.ts";
import { makeTasks } from "./task-actions.ts";
import { makeArchive } from "./archive.ts";
import { makeReopen } from "./reopen.ts";
/** How often the events of a burst redraw the sidebar, at most. */
const EVENT_REDRAW_MS = 100;
const describe = (error: unknown): string =>
error instanceof Error && error.message ? error.message : "unknown error";
// A report of the host or the chat plugin about some chats, applied by
// `apply`, which says whether it changed anything. One that moves a row, to
// another section or another place in its own, redraws at once; only what
// changes in place waits for the burst.
const reporter =
(state: SidebarState, redraw: () => void, redrawSoon: () => void) =>
(chatIds: Iterable<string>, apply: () => boolean = () => true): void => {
const ids = [...chatIds];
const before = ids.map((id) => standing(state, id));
const changed = apply();
if (ids.some((id, index) => standing(state, id) !== before[index])) redraw();
else if (changed) redrawSoon();
};
// Reads what the chat plugin knows once, into the state; a failure is logged.
const readInto = <A, E>(read: Effect.Effect<A, E>, what: string, apply: (value: A) => unknown) =>
read.pipe(
Effect.tap((value) => Effect.sync(() => apply(value))),
Effect.ignore({ log: "Warn", message: `Could not read the chat plugin's ${what}` }),
);
// The chats in one of two lists and not in the other.
const changedIn = (before: ReadonlySet<string>, after: readonly string[]): string[] => {
const now = new Set(after);
return [...before, ...after].filter((id) => before.has(id) !== now.has(id));
};
// Reads the workspace and chat lists. Every event starts its own refresh and
// the host answers a plugin's requests concurrently, so an older read can
// answer after a newer one; such a read answers None, since it would bring
// back a workspace or chat the newer one no longer lists. The list calls
// leave synchronously, in one block: the registration flush that follows
// activate must already see them. Failures map to HostError exactly as
// Host.call would.
const newestLists = (api: Api) => {
let reads = 0;
let adopted = 0;
const adopt = <A>(method: string, task: Promise<A>): Effect.Effect<A, HostError> =>
Effect.tryPromise({ try: () => task, catch: (error) => hostError(method, error) });
return Effect.fn("Sidebar.loadLists")(function* () {
const read = ++reads;
const pending = yield* Effect.sync(() => [api.host.workspaces.list({}), api.host.chats.list({})] as const);
const lists = yield* Effect.all([adopt("host/workspaces.list", pending[0]), adopt("host/chats.list", pending[1])], {
concurrency: "unbounded",
});
if (read < adopted) return Option.none();
adopted = read;
return Option.some(lists);
});
};
// Dragging and pinning chats, and the check-off that a drop into another
// section makes.
const makePlacement = Effect.fn("Sidebar.placement")(function* (state: SidebarState, redraw: () => void) {
const host = yield* Host;
const app = yield* App;
const notify = yield* Notify;
// Where the user dragged chats, kept so it survives a restart.
const savePlaced = (): Effect.Effect<void> =>
host
.call("host/storage.set", { key: PLACED_KEY, value: state.placed })
.pipe(Effect.catch((error: unknown) => notify.error(`Could not save the order of the chats: ${describe(error)}`)));
// The host hears that a chat was checked off or opened again. The row
// took the change at once; when the host refuses it, the row goes back
// to when it was checked off before (`before`).
const writeCompleted = (chatId: string, completed: boolean, before: string | null): Effect.Effect<void> =>
host.call("host/chats.update", { chatId, completed }).pipe(
Effect.catch((error: unknown) =>
Effect.sync(() => {
const task = taskOf(state, chatId);
if (task) state.tasks[task.id] = { ...task, completedAt: before };
redraw();
}).pipe(Effect.andThen(notify.error(`Could not update the chat: ${describe(error)}`))),
),
);
// A dragged chat's place follows the pointer through the list, and the
// rows glide around it.
const dragChat = (id: string, over: Over, part?: Part): Effect.Effect<void> =>
Effect.sync(() => {
if (dragOver(state, id, over, part)) redraw();
});
// The pointer of a chat's drag came onto the dock floating over the
// list's foot, or left it.
const dragOverDock = (id: string, on: boolean): Effect.Effect<void> =>
Effect.sync(() => {
if (dragOnDock(state, id, on)) redraw();
});
// A drop lands the dragged chat in its place, and the section it lands in
// sets its state. Checking off the chat on screen this way gives the
// screen to the next open chat, as the check does.
// The drop lands before anything waits: the drag's end, which comes
// right after, must find it landed. An older kernel tells only where it
// was dropped (`over`).
const dropChat = Effect.fn("Sidebar.dropChat")(function* (id: string, over?: Over) {
const successor = nextOpenChat(state, id);
const before = taskOf(state, id)?.completedAt ?? null;
const dropped = dropDragged(state, id, over);
redraw();
if (!dropped) return;
yield* savePlaced();
if (dropped.completed === undefined) return;
const current = yield* app.state;
if (dropped.completed && successor && current.chatId === id)
yield* app.select(successor.id, successor.workspaceId);
yield* writeCompleted(id, dropped.completed, before);
});
// A drag let go off the list: the chat stays where it was.
const endDragging = (): Effect.Effect<void> =>
Effect.sync(() => {
const joined = state.joining !== null;
state.joining = null;
if (endDrag(state) || joined) redraw();
});
// Pinning keeps a chat in Pinned, above the running ones, whatever it does.
const togglePin = Effect.fn("Sidebar.togglePin")(function* (chat: Chat) {
togglePinned(state, chat);
redraw();
yield* savePlaced();
});
// Snoozing keeps a row in Snoozed until `until` (epoch milliseconds), or until the user ends it when null.
const snoozeRow = Effect.fn("Sidebar.snoozeRow")(function* (chat: Chat, until: number | null) {
snooze(state, chat, until);
redraw();
yield* savePlaced();
});
const unsnoozeRow = Effect.fn("Sidebar.unsnoozeRow")(function* (chat: Chat) {
unsnooze(state, chat);
redraw();
yield* savePlaced();
});
return { savePlaced, writeCompleted, dragChat, dragOverDock, dropChat, endDragging, togglePin, snoozeRow, unsnoozeRow };
});
// Moving the sections by their headings: up and down the list, and into
// and out of the dock at its foot. The order is kept so it survives a
// restart.
const makeSectionOrder = Effect.fn("Sidebar.sectionOrder")(function* (state: SidebarState, redraw: () => void) {
const host = yield* Host;
const notify = yield* Notify;
// The heading's place follows the pointer, and the sections glide around it.
const moveSection = (id: SectionId, over: SectionOver): Effect.Effect<void> =>
Effect.sync(() => {
if (dragSection(state, id, over)) redraw();
});
const landSection = Effect.fn("Sidebar.landSection")(function* (id: SectionId) {
const moved = dropSection(state, id);
redraw();
if (!moved) return;
yield* host
.call("host/storage.set", { key: ARRANGEMENT_KEY, value: state.arrangement })
.pipe(Effect.catch((error: unknown) => notify.error(`Could not save the order of the sections: ${describe(error)}`)));
});
// A heading let go off the sidebar: the sections stay as they were.
const endSectionDrag = (): Effect.Effect<void> =>
Effect.sync(() => {
if (!state.movingSection) return;
state.movingSection = null;
redraw();
});
return { moveSection, landSection, endSectionDrag };
});
// The dock's edge let go: the height it was dragged to is kept so it survives a restart.
const makeDockResize = Effect.fn("Sidebar.dockResize")(function* (state: SidebarState, redraw: () => void) {
const host = yield* Host;
const notify = yield* Notify;
const endDockResize = Effect.fn("Sidebar.endDockResize")(function* () {
if (!state.resizingDock) return;
state.resizingDock = null;
redraw();
yield* host
.call("host/storage.set", { key: DOCK_HEIGHT_KEY, value: state.dockHeight })
.pipe(Effect.catch((error: unknown) => notify.error(`Could not save the height of the docked sections: ${describe(error)}`)));
});
return { endDockResize };
});
/** Reads a stored value of the shape `schema`; a value of another shape reads as none. */
type Stored = <S extends z.ZodType>(key: string, schema: S) => Effect.Effect<z.infer<S> | undefined, HostError>;
// The user's choices for the list, read while the list itself is read so
// that its first draw already shows them: the folded sections, the order
// of the sections, the tasks whose chats are listed under their row, where
// chats were dragged and the dock's height. What it returns puts them in place.
const makeReadSaved = (state: SidebarState, stored: Stored, notify: Effect.Success<typeof Notify>) =>
Effect.fn("Sidebar.readSaved")(function* () {
const placement = z.object({
section: z.enum(SECTIONS.map((s) => s.id)),
rank: z.number(),
chosen: z.boolean().optional(),
until: z.number().optional(),
});
const read = Effect.all(
[
stored(COLLAPSED_KEY, z.union([z.array(z.string()), z.record(z.string(), z.boolean())])),
stored(ARRANGEMENT_KEY, z.object({ list: z.array(z.string()), dock: z.array(z.string()) })),
stored(EXPANDED_KEY, z.array(z.string())),
stored(PLACED_KEY, z.record(z.string(), placement)),
stored(DOCK_HEIGHT_KEY, z.number()),
],
{ concurrency: "unbounded" },
);
// Storage that cannot be read says so; the list shows with its defaults.
const saved = yield* read.pipe(
Effect.catch((error: unknown) =>
notify.error(`The sidebar's saved layout could not be read: ${describe(error)}`).pipe(Effect.as(undefined)),
),
);
return () => {
if (!saved) return;
const [collapsed, order, expanded, placed, dockHeight] = saved;
// A saved folded set replaces the default one, in which Snoozed and Complete are folded.
if (collapsed) state.collapsed = collapsedFrom(collapsed);
if (order) state.arrangement = arrangementFrom(order);
state.expanded = new Set(expanded ?? []);
if (placed) state.placed = placed;
if (dockHeight !== undefined) state.dockHeight = dockHeight;
};
});
// The commands that pick a row of the list: the row of the chat on screen, or a row by its place.
const makeRowCommands = Effect.fn("Sidebar.rowCommands")(function* (state: SidebarState) {
const app = yield* App;
// A command on the row of the chat on screen: its own row, or its task's row (the task is
// passed when the row is a task's).
const onScreenRow = (run: (chat: Chat, task: Task | undefined) => Effect.Effect<void, unknown>) =>
Effect.gen(function* () {
const current = yield* app.state;
const shown = state.chats.find((c) => c.id === current.chatId);
if (!shown) return;
const task = isTaskRow(state, shown) ? taskOf(state, shown.id) : undefined;
const lead = task ? state.chats.find((c) => taskOf(state, c.id)?.id === task.id && leadsRow(state, c)) : shown;
if (lead) yield* run(lead, task).pipe(Effect.asVoid);
});
// Cmd+1 to Cmd+8 select by position; Cmd+9 selects the last listed row.
const selectListedCommand = (index: number): Effect.Effect<void> =>
Effect.suspend(() => {
const listed = listedChats(state);
const row = index === 8 ? listed.at(-1) : listed[index];
const chat = row ? openingChat(state, row) : undefined;
return chat ? app.select(chat.id, chat.workspaceId) : Effect.void;
});
return { onScreenRow, selectListedCommand };
});
// A chat leaves Finished for Open an hour after its run ended, and Snoozed
// when its snooze ends: after each draw, the sidebar calls `arrive` at the
// next such moment.
function timedMoves(state: SidebarState, arrive: () => void) {
let timer: ReturnType<typeof setTimeout> | undefined;
let due: number | undefined;
const follow = (now: number): void => {
const next = nextTimedMove(state, now);
if (next === due) return;
clearTimeout(timer);
due = next;
if (next === undefined) return;
timer = setTimeout(() => {
due = undefined;
arrive();
}, next - now);
};
return { follow, stop: () => clearTimeout(timer) };
}
const makeSidebar = Effect.fn("Sidebar.make")(function* () {
const host = yield* Host;
const kernel = yield* Kernel;
const app = yield* App;
const notify = yield* Notify;
const plugin = yield* Plugin;
const services = yield* Services;
const scope = yield* Effect.scope;
const state = initialState();
const views: ViewHandle[] = [];
// The chat each of ⌘1…⌘9 opens, declared to the kernel so that the key
// switches chats on its own frame instead of after a trip through this
// plugin. A host without declared actions has no `commandAction`; the
// commands' handlers open the chat either way.
const declaredChats: (string | null)[] = [];
const declareChatActions = (): void => {
const api = plugin.api;
if (!api || !("commandAction" in api) || typeof api.commandAction !== "function") return;
const listed = listedChats(state);
for (let n = 0; n < 9; n++) {
const chat = n === 8 ? listed.at(-1) : listed[n];
const key = chat ? `${chat.workspaceId}/${chat.id}` : null;
if (declaredChats[n] === key) continue;
const action = chat ? { chatId: chat.id, workspaceId: chat.workspaceId, route: "chat" } : null;
if (api.commandAction(`sidebar.openChat${n + 1}`, action)) declaredChats[n] = key;
}
};
// The draft ⌘N opens next, declared to the kernel the same way.
const declareNewChat = yield* makeNextChat(state);
// Each redraw lays the whole sidebar out again, 2 to 3 ms of the main
// thread that animations need. What the user does redraws at once. What
// the host and the chat plugin report comes in bursts (a sent prompt
// brings its status, title, usage and streaming words within a few
// frames), so an event redraws at once only when the sidebar has not
// drawn for EVENT_REDRAW_MS; otherwise the burst draws once when that
// time is up.
let eventTimer: ReturnType<typeof setTimeout> | undefined;
let drawnAt = -Infinity;
const redraw = (): void => {
if (eventTimer !== undefined) clearTimeout(eventTimer);
eventTimer = undefined;
drawnAt = Date.now();
for (const view of views) view.update();
declareChatActions();
declareNewChat();
expiry.follow(drawnAt);
};
// A snooze that ends puts its chat at the top of Open, which is saved.
const expiry = timedMoves(state, () => {
if (prunePlaced(state)) Effect.runFork(savePlaced());
redraw();
});
const redrawSoon = (): void => {
if (eventTimer !== undefined) return;
const wait = drawnAt + EVENT_REDRAW_MS - Date.now();
if (wait <= 0) redraw();
else eventTimer = setTimeout(redraw, wait);
};
const report = reporter(state, redraw, redrawSoon);
yield* Effect.addFinalizer(() => Effect.sync(() => clearTimeout(eventTimer)));
yield* Effect.addFinalizer(() => Effect.sync(expiry.stop));
// Storage may hold values the JavaScript original wrote without a schema;
// a bad shape keeps the default rather than failing the refresh.
const stored: Stored = (key, schema) =>
host.call("host/storage.get", { key }).pipe(
Effect.flatMap((result) => parse(key, schema, result.value)),
Effect.catchTag("ParseFailed", () => Effect.succeed(undefined)),
);
// The agents list leaves synchronously, like the baseline's fire-and-forget
// `api.host.agents.list({}).then(...)` in refresh(): the call must be
// recorded before the first render's transcript reads. A forked
// `host.call` would leave after those reads, flipping the host-call order.
const loadAgentsFrom = Effect.fn("Sidebar.loadAgents")(function* (pending: Promise<unknown>) {
const result = yield* Effect.tryPromise({
try: () => pending as Promise<{ agents: typeof state.agents }>,
catch: (error) => hostError("host/agents.list", error),
});
state.agents = [...result.agents];
const defaultAgent = yield* stored("defaultAgent", z.string());
if (defaultAgent && state.agents.some((a) => a.id === defaultAgent)) state.lastAgent = defaultAgent;
const first = state.agents[0];
if (!state.lastAgent && first) state.lastAgent = first.id;
redraw();
});
const { savePlaced, writeCompleted, dragChat, dragOverDock, dropChat, endDragging, togglePin, snoozeRow, unsnoozeRow } = yield* makePlacement(
state,
redraw,
);
const readSaved = makeReadSaved(state, stored, notify);
const { archive, bringBack, ...archiving } = yield* makeArchive(state, redraw, savePlaced);
// A chat that moved to another section is sorted there as any other.
const forgetMoved = Effect.fn("Sidebar.forgetMoved")(function* () {
if (prunePlaced(state)) yield* Effect.forkIn(savePlaced(), scope, { startImmediately: true });
});
const readLists = newestLists(plugin.api);
const refresh = Effect.fn("Sidebar.refresh")(function* () {
const known = new Set(state.chats.map((chat) => chat.id));
const saved = state.loaded ? undefined : yield* Effect.forkIn(readSaved(), scope);
const lists = yield* readLists();
if (Option.isNone(lists)) return;
const [workspaces, chats] = lists.value;
state.workspaces = [...workspaces.workspaces];
state.colors = workspaces.colors ?? [];
// Run events can advance a chat while the list request is in flight.
const live = new Map(state.chats.map((chat) => [chat.id, chat]));
const read = chats.chats.map((chat) => {
const current = live.get(chat.id);
return current && current.updatedAt > chat.updatedAt ? current : chat;
});
// A draft created during this read was not part of its snapshot.
const listed = new Set(read.map((chat) => chat.id));
state.chats = [...read, ...[...live.values()].filter((chat) => !known.has(chat.id) && !listed.has(chat.id))];
state.filter = state.filter.filter((id) => state.workspaces.some((w) => w.id === id));
const { tasks } = yield* host
.call("host/tasks.list", {})
.pipe(Effect.catch((error: unknown) => notify.error(`The tasks could not be read: ${describe(error)}`).pipe(Effect.as({ tasks: [] }))));
for (const task of tasks) noteTask(state, task);
if (saved) {
(yield* Fiber.join(saved))();
// What changed while the app was closed has already moved the placements on.
yield* forgetMoved();
}
state.loaded = true;
state.failed = null;
const pendingAgents = yield* Effect.sync(() => plugin.api.host.agents.list({}));
yield* Effect.forkIn(loadAgentsFrom(pendingAgents), scope);
const current = yield* app.state;
const firstWorkspace = state.workspaces[0];
if (!state.workspaces.some((w) => w.id === current.workspaceId) && firstWorkspace) {
yield* app.update({ workspaceId: firstWorkspace.id });
}
redraw();
});
// A first read that failed says so in place of the list; the next
// workspace or agent event reads again.
const loadFailed = (error: unknown): Effect.Effect<void> =>
Effect.sync(() => {
if (state.loaded) return;
state.failed = describe(error);
redraw();
});
// --- chats -------------------------------------------------------------------
const defaultWorkspace = Effect.fn("Sidebar.defaultWorkspace")(function* () {
const current = yield* app.state;
return newChatWorkspace(state, current.workspaceId);
});
const pickAgent = Effect.fn("Sidebar.pickAgent")(function* (workspaceId: string) {
const agent = newChatAgent(state, workspaceId);
if (!agent) {
yield* notify.warning("Enable an agent in Settings first.");
return null;
}
yield* Effect.forkIn(
host
.call("host/storage.set", { key: "defaultAgent", value: agent })
.pipe(Effect.ignore({ log: "Warn", message: "Could not remember the default agent" })),
scope,
{ startImmediately: true },
);
return agent;
});
const newChat = Effect.fn("Sidebar.newChat")(function* (workspaceId: string) {
const agent = yield* pickAgent(workspaceId);
if (!agent) return;
const inUse = chatsInUse(state);
// Cmd+N and the New chat row run this as a command, whose failures the
// runtime only logs, so it tells the user itself.
const chat = yield* host
.call("host/chats.create", { workspaceId, agentId: agent, inUse })
.pipe(Effect.catch((error: unknown) => notify.error(`Could not create a chat: ${describe(error)}`).pipe(Effect.as(undefined))));
if (!chat) return;
applyChatChange(state, chat);
redraw();
yield* app.update({ chatId: chat.id, workspaceId, route: "chat", shared: { selectedChat: chat } });
yield* Effect.forkIn(refresh(), scope, { startImmediately: true });
});
// Cmd+O runs this as a command, whose failures the runtime only logs, so
// it tells the user itself, as the picker's row needs too.
const addWorkspace = Effect.fn("Sidebar.addWorkspace")(function* () {
const workspace = yield* promise("pickFolder", () => plugin.api.pickFolder()).pipe(
Effect.flatMap((picked) =>
picked?.path ? host.call("host/workspaces.add", { path: picked.path }) : Effect.succeed(undefined),
),
Effect.catch((error: unknown) =>
notify.error(`Could not add the workspace folder: ${describe(error)}`).pipe(Effect.as(undefined)),
),
);
if (!workspace) return;
// The list shows the new folder alone, and the center opens a draft
// there: the chat a user adds a folder for.
state.filter = [workspace.id];
yield* newChat(workspace.id);
});
// Remove asks first: the first click arms it and says how many chats go
// with the workspace, the second removes it. The pointer leaving disarms it.
const armRemove = (workspaceId: string | null): Effect.Effect<void> =>
Effect.sync(() => {
if (state.removing === workspaceId) return;
state.removing = workspaceId;
redraw();
});
const removeWorkspace = Effect.fn("Sidebar.removeWorkspace")(function* (workspace: Workspace) {
state.removing = null;
// The workspace-changed event that follows triggers the refresh and redraw.
const removed = yield* host.call("host/workspaces.remove", { workspaceId: workspace.id }).pipe(
Effect.as(true),
Effect.catch((error: unknown) =>
notify.error(`Could not remove ${workspace.name}: ${describe(error)}`).pipe(Effect.as(false)),
),
);
if (removed) state.filter = state.filter.filter((id) => id !== workspace.id);
redraw();
});
// A workspace's mark: a folder in `color`, or (`null`) its project icon.
// The workspace-changed event that follows redraws.
const setColor = Effect.fn("Sidebar.setColor")(function* (workspaceId: string, color: PresetColor | null) {
yield* host
.call("host/workspaces.set_color", { workspaceId, color })
.pipe(Effect.catch((error) => notify.error(`Could not change the workspace's icon: ${describe(error)}`)));
});
const setFilter = Effect.fn("Sidebar.setFilter")(function* (workspaceIds: readonly string[]) {
state.filter = [...workspaceIds];
state.showAll = {};
const [only] = workspaceIds;
if (only && workspaceIds.length === 1) yield* app.update({ workspaceId: only });
redraw();
});
// Folding a section hides its rows under the heading; the folded set is
// kept so it survives a restart.
const toggleSection = Effect.fn("Sidebar.toggleSection")(function* (id: SectionId) {
if (state.collapsed[id]) delete state.collapsed[id];
else state.collapsed[id] = true;
redraw();
// Every section is named, folded or not, so a section added later takes its own default.
yield* host
.call("host/storage.set", {
key: COLLAPSED_KEY,
value: Object.fromEntries(SECTIONS.map((s) => [s.id, !!state.collapsed[s.id]])),
})
.pipe(Effect.catch((error: unknown) => notify.error(`Could not save the folded sections: ${describe(error)}`)));
});
// --- renaming and checking off -----------------------------------------------
const { startRename, cancelRename, commitRename } = yield* makeRename(state, redraw);
// Checking off takes at once: the chat is complete here from the click
// and moves to Complete, and the host is told. Checking off the chat on
// screen gives the screen to the next open chat.
const toggleCompleted = Effect.fn("Sidebar.toggleCompleted")(function* (chat: Chat) {
const completed = !completedOf(state, chat);
const before = taskOf(state, chat.id)?.completedAt ?? null;
const current = yield* app.state;
const successor = completed && taskOf(state, chat.id)?.id === (current.chatId ? taskOf(state, current.chatId)?.id : undefined)
? nextOpenChat(state, chat.id)
: undefined;
setCompleted(state, chat.id, completed);
redraw();
yield* forgetMoved();
if (successor) yield* app.select(successor.id, successor.workspaceId);
yield* writeCompleted(chat.id, completed, before);
});
const submitDraft = Effect.fn("Sidebar.submitDraft")(function* (chatId: string, queue: boolean) {
if (!state.chat || state.submitting.has(chatId)) return;
state.submitting.add(chatId);
redraw();
yield* state.chat.submitDraft({ chatId, queue }).pipe(
Effect.catch((error) => notify.error(`Could not submit the draft: ${describe(error)}`)),
Effect.ensuring(
Effect.sync(() => {
state.submitting.delete(chatId);
redrawSoon();
}),
),
);
});
// A queued chat leaves the queue and goes back to the drafts.
const unqueue = Effect.fn("Sidebar.unqueue")(function* (chatId: string) {
if (!state.chat) return;
yield* state.chat
.unqueue({ chatId })
.pipe(Effect.catch((error) => notify.error(`Could not take the chat out of the queue: ${describe(error)}`)));
});
// The pointer rests on a chat's row: the chat plugin reads its transcript
// and builds its pane now, so that the click shows it at once. A failed
// read changes nothing and is logged.
const prefetch = (chatId: string): Effect.Effect<void> =>
state.chat
? state.chat
.prefetch({ chatId })
.pipe(Effect.ignore({ log: "Warn", message: "The chat plugin could not read the transcript ahead" }))
: Effect.void;
// The chat a check-off of the chat on screen would show next.
const successor = (chatId: string): Chat | undefined => {
const chat = state.chats.find((c) => c.id === chatId);
return chat && !completedOf(state, chat) ? nextOpenChat(state, chat.id) : undefined;
};
// Resting on the row of the chat on screen, which is read already, reads
// the chat its check-off would show, so that the check-off shows it at once.
const restRead = Effect.fn("Sidebar.restRead")(function* (chatId: string) {
const current = yield* app.state;
const read = current.chatId === chatId ? successor(chatId)?.id : chatId;
if (read) yield* prefetch(read);
});
const { restOn, leaveRow } = restingReads(restRead, scope);
// Cmd held may be for Cmd+Shift+M: the chat it would show is read now.
const readAhead = Effect.fn("Sidebar.readAhead")(function* () {
const current = yield* app.state;
const next = current.route === "chat" && current.chatId ? successor(current.chatId) : undefined;
if (next) yield* prefetch(next.id);
});
const ensurePreview = yield* makePeek(state, redrawSoon);
// --- events and commands -----------------------------------------------------
// Queued chats, draft titles and starting chats come from the chat plugin while it runs:
// read once, then followed through its events. One episode per provider:
// the previous follow ends when the provider goes.
const followChat = Effect.fn("Sidebar.followChat")(function* () {
yield* services.when<typeof ChatService>("divergence/chat").pipe(
Stream.runForEach((option) =>
Effect.gen(function* () {
if (state.follow) {
yield* Fiber.interrupt(state.follow);
state.follow = undefined;
}
if (Option.isNone(option)) {
state.chat = undefined;
redraw();
return;
}
const client: EffectClient<typeof ChatService> = option.value;
state.chat = client;
state.follow = yield* Effect.forkIn(
Effect.all(
[
client.on("queuedChanged").pipe(
Stream.runForEach((queued) =>
Effect.sync(() =>
report(changedIn(state.queued, queued), () => {
state.queued = new Set(queued);
return true;
}),
).pipe(Effect.andThen(forgetMoved())),
),
),
client.on("draftTitlesChanged").pipe(
Stream.runForEach((drafts) =>
Effect.sync(() => {
state.draftTitles = { ...drafts };
redrawSoon();
}),
),
),
client.on("startingChanged").pipe(
Stream.runForEach((starting) =>
Effect.sync(() =>
// A chat that starts moves to Running with the prompt
// box, at once, in the place it keeps once the host
// reports the run.
report(changedIn(state.starting, starting), () => {
for (const id of starting) if (!state.starting.has(id)) state.sent[id] = Date.now();
state.starting = new Set(starting);
return true;
}),
).pipe(Effect.andThen(forgetMoved())),
),
),
],
{ concurrency: "unbounded", discard: true },
),
scope,
{ startImmediately: true },
);
// A provider that goes away mid-read leaves the last titles, and the
// failure is logged.
yield* Effect.all(
[
readInto(client.queued({}), "queue", (queued) => (state.queued = new Set(queued))),
readInto(client.draftTitles({}), "draft titles", (drafts) => (state.draftTitles = { ...drafts })),
readInto(client.starting({}), "starting chats", (starting) => (state.starting = new Set(starting))),
],
{ concurrency: "unbounded", discard: true },
);
redraw();
}),
),
Effect.forkIn(scope, { startImmediately: true }),
);
});
yield* followChat();
const chatChanged = Effect.fn("Sidebar.chatChanged")(function* (event: HostEvents["chat_changed"]) {
report([event.chat.id], () => {
applyChatChange(state, event.chat);
if (state.previews[event.chat.id]?.failed) delete state.previews[event.chat.id];
return true;
});
yield* forgetMoved();
});
const chatRemoved = Effect.fn("Sidebar.chatRemoved")(function* (event: HostEvents["chat_removed"]) {
applyChatRemoved(state, event.chatId);
redraw();
yield* forgetMoved();
});
const transcriptReset = Effect.fn("Sidebar.transcriptReset")(function* (event: HostEvents["transcript_reset"]) {
applyTranscriptReset(state, event.chatId);
redrawSoon();
});
const agentEvent = Effect.fn("Sidebar.agentEvent")(function* (event: HostEvents["agent"]) {
report([event.chatId], () => applyAgentEvent(state, event));
});
const newChatCommand = Effect.fn("Sidebar.newChatCommand")(function* () {
const workspaceId = yield* defaultWorkspace();
if (workspaceId) yield* newChat(workspaceId);
});
const toggleCompletedCommand = Effect.fn("Sidebar.toggleCompletedCommand")(function* () {
const current = yield* app.state;
const chat = state.chats.find((c) => c.id === current.chatId);
if (chat) yield* toggleCompleted(chat);
});
// Cmd+W closes the chat on screen the way its section suggests: a draft
// is archived, a queued chat leaves the queue and is archived, and any
// other chat is checked off. The screen then goes to the next open chat
// in the list, or the one above when it was the last.
const closeChatCommand = Effect.fn("Sidebar.closeChatCommand")(function* () {
const current = yield* app.state;
const chat = state.chats.find((c) => c.id === current.chatId);
if (!chat) return;
// In a task, Cmd+W closes the focused pane's active tab (document 2).
if (isTaskRow(state, chat)) return yield* kernel.call("run_command", { id: "chat.closeTab" }).pipe(Effect.asVoid);
const section = sectionOf(state, chat);
// Reopen Closed Chat (Cmd+Shift+T) brings back what this puts away.
if (section !== "drafts" && section !== "queued" && !completedOf(state, chat)) {
rememberClosed(state, chat.id, null);
return yield* toggleCompleted(chat);
}
// Archiving the chat on screen moves the screen itself.
if (section === "queued") yield* unqueue(chat.id);
if (section === "drafts" || section === "queued") return yield* archive(chat, true);
const next = nextOpenChat(state, chat.id);
if (next) yield* app.select(next.id, next.workspaceId);
});
return {
...(yield* makeTasks(state, redraw, dropChat)),
...(yield* makeReopen(state, bringBack, toggleCompleted)),
...(yield* makeRowCommands(state)),
...archiving,
...(yield* makeSectionOrder(state, redraw)),
...(yield* makeDockResize(state, redraw)),
state,
views,
refresh,
runCommand: (id: string) => kernel.call("run_command", { id }).pipe(Effect.asVoid),
nativeApp: plugin.api.app,
select: (chatId: string, workspaceId: string): Effect.Effect<void> => app.select(chatId, workspaceId),
route: (name: string): Effect.Effect<void> => app.route(name),
newChat,
addWorkspace,
armRemove,
removeWorkspace,
loadFailed,
setColor,
setFilter,
toggleSection,
dragChat,
dragOverDock,
dropChat,
endDragging,
togglePin,
snoozeRow,
unsnoozeRow,
startRename,
cancelRename,
commitRename,
archive,
submitDraft,
unqueue,
prefetch,
readAhead,
restOn,
leaveRow,
toggleCompleted,
toggleCompletedCommand,
closeChatCommand,
ensurePreview,
chatChanged,
chatRemoved,
transcriptReset,
agentEvent,
newChatCommand,
declareChatActions,
};
});
export class Sidebar extends Context.Service<Sidebar, Effect.Success<ReturnType<typeof makeSidebar>>>()(
"sidebar/Sidebar",
) {
static readonly layer = Layer.effect(Sidebar, makeSidebar());
}
No comments yet.