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

  • Control chats chats.controlHighCreates chats, sends prompts and cancels runs.Add and remove workspaces, and create, rename, check off and archive chats
  • Run other plugins' commands commands.runHighRuns commands of other plugins.Close the tab on screen with Cmd+W when its chat is part of a task
  • Read chats chats.readMediumReads your transcripts and chat lists.List workspaces and chats, and follow them as agents work
  • Show panels ui.slotsAlways grantedShows views in the listed parts of the window.Draw the sidebarSlots: left

Files

controller.ts28.9 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, SectionId, SidebarState } from "./sections.ts";
import { restingReads } from "./rest.ts";
import type { Task } from "divergence/protocol";
import {
  COLLAPSED_KEY,
  EXPANDED_KEY,
  PLACED_KEY,
  SECTIONS,
  applyAgentEvent,
  applyChatChange,
  applyChatRemoved,
  applyTranscriptReset,
  dragOver,
  dropDragged,
  endDrag,
  initialState,
  listedChats,
  nextOpenChat,
  prunePlaced,
  recentAgent,
  sectionOf,
  togglePinned,
  completedOf,
  forgetTask,
  isTaskRow,
  leadsRow,
  noteTask,
  openingChat,
  setCompleted,
  taskOf,
} from "./sections.ts";
import { createPreview, transcriptPreview } from "./preview.ts";
import { makeTasks } from "./task-actions.ts";
import { makeArchive } from "./archive.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 host that does not know a method answers it with JSON-RPC's
// method-not-found code, or, before it had one for host methods, with an
// internal error that names the method as unknown.
export const isUnknownMethod = (error: HostError): boolean =>
  error._tag === "HostCallFailed" && (error.code === -32601 || error.message.startsWith("unknown host method"));

// 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.
  const writeCompleted = (chatId: string, completed: boolean): Effect.Effect<void> =>
    host
      .call("host/chats.update", { chatId, completed })
      .pipe(Effect.catch((error: unknown) => 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): Effect.Effect<void> =>
    Effect.sync(() => {
      if (dragOver(state, id, over)) 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 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);
  });

  // 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();
  });

  return { savePlaced, writeCompleted, dragChat, dropChat, endDragging, togglePin };
});

// 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+9: the chat in that row of the list, top to bottom.
  const selectListedCommand = (index: number): Effect.Effect<void> =>
    Effect.suspend(() => {
      const row = listedChats(state)[index];
      const chat = row ? openingChat(state, row) : undefined;
      return chat ? app.select(chat.id, chat.workspaceId) : Effect.void;
    });

  return { onScreenRow, selectListedCommand };
});

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 = 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;
    }
  };
  // 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();
  };
  const redrawSoon = (): void => {
    if (eventTimer !== undefined) return;
    const wait = drawnAt + EVENT_REDRAW_MS - Date.now();
    if (wait <= 0) redraw();
    else eventTimer = setTimeout(redraw, wait);
  };
  yield* Effect.addFinalizer(() => Effect.sync(() => clearTimeout(eventTimer)));

  // Storage may hold values the JavaScript original wrote without a schema;
  // a bad shape keeps the default rather than failing the refresh.
  const stored = <S extends z.ZodType>(key: string, schema: S): Effect.Effect<z.infer<S> | undefined, HostError> =>
    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();
  });

  // The folded sections and the chats the user dragged come back from
  // storage after the first draw.
  const loadCollapsed = Effect.fn("Sidebar.loadCollapsed")(function* () {
    const saved = yield* stored(COLLAPSED_KEY, z.array(z.string()));
    for (const section of SECTIONS) if (saved?.includes(section.id)) state.collapsed[section.id] = true;
    const expanded = yield* stored(EXPANDED_KEY, z.array(z.string()));
    state.expanded = new Set(expanded ?? []);
    const placed = yield* stored(
      PLACED_KEY,
      z.record(
        z.string(),
        z.object({ section: z.enum(SECTIONS.map((s) => s.id)), rank: z.number(), chosen: z.boolean().optional() }),
      ),
    );
    if (placed) {
      state.placed = placed;
      // What changed while the app was closed has already moved them on.
      if (prunePlaced(state)) yield* savePlaced();
    }
    redraw();
  });

  const { savePlaced, writeCompleted, dragChat, dropChat, endDragging, togglePin } = yield* makePlacement(
    state,
    redraw,
  );
  const { archive, ...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 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]));
    state.chats = 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(state.chats.map((chat) => chat.id));
    state.chats.push(...[...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 (!state.loaded) yield* Effect.forkIn(loadCollapsed(), scope);
    state.loaded = true;
    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();
  });

  // --- chats -------------------------------------------------------------------

  const defaultWorkspace = Effect.fn("Sidebar.defaultWorkspace")(function* () {
    const current = yield* app.state;
    return (
      (state.filter.length === 1 ? state.filter[0] : undefined) ??
      current.workspaceId ??
      state.workspaces[0]?.id ??
      null
    );
  });

  const pickAgent = Effect.fn("Sidebar.pickAgent")(function* (workspaceId: string) {
    const first = state.agents[0];
    const agent = recentAgent(state, workspaceId) ?? state.lastAgent ?? first?.id;
    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;
    // A draft with typed text or a place in the queue is in use: New chat
    // from it opens another draft rather than the same one.
    const inUse = [...Object.keys(state.draftTitles), ...state.queued];
    const chat = yield* host.call("host/chats.create", { workspaceId, agentId: agent, inUse });
    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).pipe(
      Effect.catch((error: unknown) => notify.error(`Could not open a chat in the new folder: ${describe(error)}`)),
    );
  });

  const removeWorkspace = Effect.fn("Sidebar.removeWorkspace")(function* (workspace: Workspace) {
    // The workspace-changed event that follows triggers the refresh and redraw.
    yield* host.call("host/workspaces.remove", { workspaceId: workspace.id });
    state.filter = state.filter.filter((id) => id !== workspace.id);
  });

  // 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();
    yield* host
      .call("host/storage.set", {
        key: COLLAPSED_KEY,
        value: SECTIONS.filter((s) => state.collapsed[s.id]).map((s) => s.id),
      })
      .pipe(Effect.catch((error: unknown) => notify.error(`Could not save the folded sections: ${describe(error)}`)));
  });

  // --- renaming and checking off -----------------------------------------------

  const commitRename = Effect.fn("Sidebar.commitRename")(function* () {
    const editing = state.editing;
    if (!editing) return;
    state.editing = null;
    redraw();
    // A task row's name is the task's; clearing it goes back to its first
    // chat's title (document 1).
    const renamed: Effect.Effect<unknown, HostError> = editing.task
      ? host.call("host/tasks.update", { taskId: editing.task, title: editing.title.trim() || null })
      : host.call("host/chats.update", { chatId: editing.id, title: editing.title.trim() || "New Chat" });
    yield* renamed.pipe(Effect.catch((error: unknown) => notify.error(`Rename failed: ${describe(error)}`)));
  });

  // 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 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);
  });

  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;
  const { restOn, leaveRow } = restingReads(prefetch, scope);

  // Latest model activity for a chat's live line: the end of the chat,
  // read once and only for chats a row actually showed, never the whole
  // transcript (an older host without `chats.peek` gives the whole one).
  // Any other failure of the peek is shown, not read around.
  const ensurePreview = Effect.fn("Sidebar.ensurePreview")(function* (chatId: string) {
    const preview = (state.previews[chatId] ??= createPreview());
    if (preview.loading || preview.revision) return;
    preview.loading = true;
    yield* host.call("host/chats.peek", { chatId, limit: 20 }).pipe(
      Effect.catchIf(isUnknownMethod, () => host.call("host/chats.transcript", { chatId })),
      Effect.tap((result) =>
        Effect.sync(() => {
          // Streaming activity or a reset since this read takes precedence.
          if (state.previews[chatId] === preview && !preview.revision) {
            Object.assign(preview, transcriptPreview(result.items), { loading: true });
            redrawSoon();
          }
        }),
      ),
      Effect.catch((error: unknown) => notify.error(`Chat preview unavailable: ${describe(error)}`)),
    );
  });

  // --- 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(() => {
                      state.queued = new Set(queued);
                      redrawSoon();
                    }).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; one the host now reports waits for the burst.
                      const started = starting.some((id) => !state.starting.has(id));
                      state.starting = new Set(starting);
                      if (started) redraw();
                      else redrawSoon();
                    }).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(
            [
              client.queued({}).pipe(
                Effect.tap((queued) =>
                  Effect.sync(() => {
                    state.queued = new Set(queued);
                  }),
                ),
                Effect.ignore({ log: "Warn", message: "Could not read the chat plugin's queue" }),
              ),
              client.draftTitles({}).pipe(
                Effect.tap((drafts) =>
                  Effect.sync(() => {
                    state.draftTitles = { ...drafts };
                  }),
                ),
                Effect.ignore({ log: "Warn", message: "Could not read the chat plugin's draft titles" }),
              ),
              client.starting({}).pipe(
                Effect.tap((starting) =>
                  Effect.sync(() => {
                    state.starting = new Set(starting);
                  }),
                ),
                Effect.ignore({ log: "Warn", message: "Could not read the chat plugin's starting chats" }),
              ),
            ],
            { concurrency: "unbounded", discard: true },
          );
          redraw();
        }),
      ),
      Effect.forkIn(scope, { startImmediately: true }),
    );
  });
  yield* followChat();

  const chatChanged = Effect.fn("Sidebar.chatChanged")(function* (event: HostEvents["chat_changed"]) {
    applyChatChange(state, event.chat);
    redrawSoon();
    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"]) {
    if (applyAgentEvent(state, event)) redrawSoon();
  });

  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);
    if (section !== "drafts" && section !== "queued" && !completedOf(state, chat)) return yield* toggleCompleted(chat);
    const next = nextOpenChat(state, chat.id);
    if (section === "queued") yield* unqueue(chat.id);
    if (section === "drafts" || section === "queued") yield* archive(chat);
    if (next) yield* app.select(next.id, next.workspaceId);
  });

  return {
    ...(yield* makeTasks(state, redraw, dropChat)),
    ...(yield* makeRowCommands(state)),
    ...archiving,
    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,
    removeWorkspace,
    setColor,
    setFilter,
    toggleSection,
    dragChat,
    dropChat,
    endDragging,
    togglePin,
    commitRename,
    archive,
    submitDraft,
    unqueue,
    prefetch,
    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());
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.7latestNov 21, 2026>=5 <6100.9 KB4 permissionsListed
0.2.6Nov 16, 2026>=5 <6100.6 KB4 permissionsListed
0.2.5Nov 11, 2026>=5 <665.1 KB4 permissionsListed
0.2.4Nov 9, 2026>=5 <660.4 KB4 permissionsListed
0.2.3Oct 27, 2026>=2 <426.1 KB3 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.