Official

chat

Built-in chat UI (JavaScript UI plugin).

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/chat@0.2.6

Permissions in 0.2.6

  • Control chats chats.controlHighCreates chats, sends prompts and cancels runs.Send prompts, answer agent questions, and create, change, fork, revert, stop and group chats
  • Run other plugins' commands commands.runHighRuns commands of other plugins.Run the sidebar's New chat command from the title bar
  • Read chats chats.readMediumReads your transcripts and chat lists.Show workspaces, tasks, chats and transcripts, and follow them as agents work
  • Read files fs.readMediumReads files in the listed places.Suggest workspace files for @ mentionsPlaces: the open workspace
  • Show panels ui.slotsAlways grantedShows views in the listed parts of the window.Draw the chat grid, the title bar, and the Session panel with its rail buttonSlots: centertitlerailright

Files

layout.ts26.9 KB
// The tasks and the side split the host keeps (specs/tasks-and-splits/05-what-it-is-made-of.md),
// as the chat plugin draws them, and what its tab strips, buttons and keys
// ask the host to change. The host owns every layout: this module only
// mirrors what its events say and sends intents.
import * as Effect from "effect/Effect";
import type { Chat } from "divergence";
import type { ClosedTab, Layout, Pane, PlaceTarget, SideSplit, Tab, Task } from "divergence/protocol";
import type { Controller } from "./controller.ts";
import { openNewTab } from "./newtab.tsx";

/** No pane is narrower or shorter than this (document 2, Limits). */
export const MIN_PANE_WIDTH = 120;
export const MIN_PANE_HEIGHT = 100;
/** The room between two panes side by side: 0.375rem. */
export const PANE_GAP = 5.625;
/** How many closed chats a task remembers for Cmd+Shift+T. */
const CLOSED_KEPT = 10;

/** What the plugin knows of the host's layouts. */
export interface Layouts {
  tasks: Record<string, Task>;
  /** Each chat's task, from the tabs of every task's layout. */
  homes: Record<string, string>;
  side: SideSplit | null;
  /** The chats each task closed, the last first. */
  closed: Record<string, ClosedTab[]>;
  /** A tab whose kind asked before closing, and its question, while the user decides. */
  asking: { tab: Tab; question: string } | null;
  /** The tab whose menu is open, with the plugins' entries for it once they come. */
  menu: { tab: Tab; paneId: string; entries: readonly MenuEntry[] } | null;
  /** A tab being carried, and the gap it opens in a strip while it is over one. */
  carried: { tab: Tab; gap: { paneId: string; index: number } | null } | null;
  /** The layout keys last reported to the kernel, as JSON, so a draw reports only a change. */
  reported: string;
  /** The pane last focused is the side split's, not the task's: the pane commands act there. */
  sideFocused: boolean;
}

/** A plugin's command placed in the tab menu (`contributes.menus.tab`). */
export interface MenuEntry {
  readonly id: string;
  readonly title: string;
}

export const emptyLayouts = (): Layouts => ({ tasks: {}, homes: {}, side: null, closed: {}, asking: null, menu: null, carried: null, reported: "", sideFocused: false });

/** Every pane of a layout, top to bottom and left to right. */
export function panesOf(layout: Layout): Pane[] {
  return layout.kind === "pane" ? [layout] : layout.children.flatMap((child) => panesOf(child.layout));
}

export function tabsOf(layout: Layout): Tab[] {
  return panesOf(layout).flatMap((pane) => pane.tabs);
}

export const chatOf = (tab: Tab | null | undefined): string | null => (tab?.kind === "chat" ? tab.chatId : null);

export const sameTab = (a: Tab, b: Tab): boolean =>
  a.kind === "chat" ? b.kind === "chat" && b.chatId === a.chatId : b.kind === "item" && b.id === a.id;

/** The pane that holds a chat. */
export function paneWith(layout: Layout, chatId: string): Pane | null {
  return panesOf(layout).find((pane) => pane.tabs.some((tab) => chatOf(tab) === chatId)) ?? null;
}

/** The panes whose top edge is the layout's: their tab strips sit in the title strip. */
export function topPanes(layout: Layout): Pane[] {
  if (layout.kind === "pane") return [layout];
  if (layout.direction === "column") return topPanes(layout.children[0]!.layout);
  return layout.children.flatMap((child) => topPanes(child.layout));
}

/** How many chats a task has. */
export function chatCount(task: Task): number {
  return tabsOf(task.layout.root).filter((tab) => tab.kind === "chat").length;
}

/** Whether a task's tabs can close: the side split's always can, and a task's when it has more
 * than one chat or a tab that is not a chat (a chat's only tab has nothing to close into). */
export function canCloseTabs(task: Task): boolean {
  return task.id === "side" || chatCount(task) > 1 || panesOf(task.layout.root).some((pane) => pane.tabs.some((tab) => tab.kind === "item"));
}

/** Whether the task is more than one plain chat: it then draws strips and panes of its own. */
export function isLaidOut(task: Task): boolean {
  const root = task.layout.root;
  return root.kind === "split" || root.tabs.length > 1;
}

/** Records a task the host sent, and the homes of its chats. */
export function noteTask(layouts: Layouts, task: Task): void {
  const before = layouts.tasks[task.id];
  if (before) for (const tab of tabsOf(before.layout.root)) if (tab.kind === "chat") delete layouts.homes[tab.chatId];
  layouts.tasks[task.id] = task;
  for (const tab of tabsOf(task.layout.root)) if (tab.kind === "chat") layouts.homes[tab.chatId] = task.id;
}

export function forgetTask(layouts: Layouts, taskId: string): void {
  const task = layouts.tasks[taskId];
  if (!task) return;
  for (const tab of tabsOf(task.layout.root)) if (tab.kind === "chat" && layouts.homes[tab.chatId] === taskId) delete layouts.homes[tab.chatId];
  delete layouts.tasks[taskId];
}

/** The task of the chat on screen. */
export function taskOnScreen(c: Controller): Task | null {
  const chatId = c.api.app.state().chatId;
  const home = chatId ? c.state.layouts.homes[chatId] : undefined;
  return home ? (c.state.layouts.tasks[home] ?? null) : null;
}

/** The chats the window shows: on the chat route, the chat in the center and the active tab of
 * every pane of its task and of the side split while that is open. */
export function chatsOnScreen(c: Controller): Set<string> {
  const { route, chatId } = c.api.app.state();
  if (route !== "chat" || !chatId) return new Set();
  const side = c.state.layouts.side;
  const roots = [taskOnScreen(c)?.layout.root, side?.open ? side.layout?.root : undefined];
  const shown = roots.flatMap((root) => (root ? panesOf(root).flatMap((pane) => chatOf(pane.active) ?? []) : []));
  return new Set([chatId, ...shown]);
}

/** The chat panes a fixed retained presentation needs in order to show its complete task. */
export function presentationChats(c: Controller, chatId: string): Set<string> {
  const home = c.state.layouts.homes[chatId];
  const task = home ? c.state.layouts.tasks[home] : undefined;
  if (!task) return new Set([chatId]);
  const selected = (pane: Pane) => {
    const own = pane.tabs.find((tab) => tab.kind === "chat" && tab.chatId === chatId);
    return chatOf(own ?? pane.active);
  };
  const shown = panesOf(task.layout.root).flatMap((pane) => selected(pane) ?? []);
  const side = sideOnScreen(c.state.layouts, task, c.state.chats);
  if (side) shown.push(...panesOf(side.task.layout.root).flatMap((pane) => selected(pane) ?? []));
  return new Set([chatId, ...shown]);
}

/** Whether a side split tab belongs on screen with `task` (document 3): one of the task's, a
 * workspace's item (a file, a terminal) beside a task with a chat of that workspace, or an item of
 * the window. */
function belongs(layouts: Layouts, task: Task, tab: Tab, chats: Readonly<Record<string, Chat>>): boolean {
  if (tab.chatId) return layouts.homes[tab.chatId] === task.id;
  if (tab.kind !== "item" || !tab.workspaceId) return true;
  return tabsOf(task.layout.root).some((t) => t.kind === "chat" && chats[t.chatId]?.workspaceId === tab.workspaceId);
}

/** The side split as it shows with `task`, as a task of its own whose panes hold only the tabs
 * that belong on screen; null while it is closed or has nothing to show. */
export function sideOnScreen(layouts: Layouts, task: Task, chats: Readonly<Record<string, Chat>>): { split: SideSplit; task: Task } | null {
  const side = layouts.side;
  if (!side?.open || !side.layout) return null;
  const visible = (layout: Layout): Layout | null => {
    if (layout.kind === "pane") {
      const tabs = layout.tabs.filter((tab) => belongs(layouts, task, tab, chats));
      if (!tabs.length) return null;
      return { ...layout, tabs, active: tabs.find((tab) => sameTab(tab, layout.active)) ?? tabs[0]! };
    }
    const children = layout.children.flatMap((child) => {
      const inner = visible(child.layout);
      return inner ? [{ ...child, layout: inner }] : [];
    });
    if (!children.length) return null;
    if (children.length === 1) return children[0]!.layout;
    const total = children.reduce((sum, child) => sum + child.share, 0);
    return { ...layout, children: children.map((child) => ({ ...child, share: child.share / total })) };
  };
  const root = visible(side.layout.root);
  if (!root) return null;
  return { split: side, task: { ...task, id: "side", layout: { root, focused: side.layout.focused } } };
}

/** Whether the side split holds anything for `task`, open or not: its toggle shows then. */
export function sideHasTabs(layouts: Layouts, task: Task, chats: Readonly<Record<string, Chat>>): boolean {
  const side = layouts.side;
  const tabs = side?.layout ? tabsOf(side.layout.root) : [];
  return tabs.some((tab) => belongs(layouts, task, tab, chats));
}

/** Immutable layout input of one retained destination; host events replace these values. */
export type PresentationLayout = {
  task: Task | undefined;
  side: ReturnType<typeof sideOnScreen>;
  hasSideTabs: boolean;
};

export function presentationLayout(c: Controller, chatId: string): PresentationLayout {
  const home = c.state.layouts.homes[chatId];
  const task = home ? c.state.layouts.tasks[home] : undefined;
  return {
    task,
    side: task ? sideOnScreen(c.state.layouts, task, c.state.chats) : null,
    hasSideTabs: task ? sideHasTabs(c.state.layouts, task, c.state.chats) : false,
  };
}

/** The pane that has the keyboard in the task on screen. */
export function focusedPane(task: Task): Pane | null {
  return panesOf(task.layout.root).find((pane) => pane.id === task.layout.focused) ?? panesOf(task.layout.root)[0] ?? null;
}

/** Whether a pane is the side split's. */
function inSide(c: Controller, paneId: string): boolean {
  const layout = c.state.layouts.side?.layout;
  return !!layout && panesOf(layout.root).some((pane) => pane.id === paneId);
}

/** The pane the user last focused, the side split's or the task on screen's, and its task (the
 * side split's as a task of its own): what Cmd+W, Cmd+T and the split keys act on. */
export function focusedTarget(c: Controller): { task: Task; pane: Pane } | null {
  const task = taskOnScreen(c);
  if (!task) return null;
  const side = c.state.layouts.side;
  if (c.state.layouts.sideFocused && side?.open && side.layout) {
    const pane = focusedPane({ ...task, id: "side", layout: side.layout });
    if (pane) return { task: { ...task, id: "side", layout: side.layout }, pane };
  }
  const pane = focusedPane(task);
  return pane ? { task, pane } : null;
}

/** Which chats Ctrl+Tab cycles through: the chat tabs of the task on screen when it has two or
 * more, else every chat, and never one the side split shows. */
export function switchable(c: Controller): (chatId: string) => boolean {
  const chatsIn = (layout: Layout | undefined) =>
    new Set(layout ? panesOf(layout).flatMap((pane) => pane.tabs.flatMap((tab) => chatOf(tab) ?? [])) : []);
  const side = chatsIn(c.state.layouts.side?.layout?.root);
  const task = chatsIn(taskOnScreen(c)?.layout.root);
  // A draft is a row of its own, never in the task, and the user starts one to come back to it.
  const draft = (chatId: string) => {
    const chat = c.state.chats[chatId];
    return !!chat && c.isDraft(chat);
  };
  return (chatId) => !side.has(chatId) && (task.size < 2 || task.has(chatId) || draft(chatId));
}

/** Equalize Splits: every split of the task on screen and of the side split equal again. */
export const equalizeSplits = Effect.fn("Chat.equalizeSplits")(function* (c: Controller) {
  yield* c.host.call("host/layouts.equalize", { onScreen: taskOnScreen(c)?.id ?? null });
});

/** Whether the pane can be split again in that direction (document 2, Limits): the task has
 * room for another pane, and each half of this one keeps the smallest size. */
export function canSplit(task: Task, direction: "right" | "down", size: { width: number; height: number } | undefined): boolean {
  if (!size) return true;
  return direction === "right" ? size.width / 2 >= MIN_PANE_WIDTH : size.height / 2 >= MIN_PANE_HEIGHT;
}

// --- reading the host ----------------------------------------------------------

/** Reads every task and the side split once, at start. */
export const loadLayouts = Effect.fn("Chat.loadLayouts")(function* (c: Controller) {
  const [{ tasks }, side] = yield* Effect.all(
    [c.host.call("host/tasks.list", {}), c.host.call("host/layouts.side", {})],
    { concurrency: "unbounded" },
  );
  for (const task of tasks) noteTask(c.state.layouts, task);
  c.state.layouts.side = side;
  redraw(c);
});

/** A task changed or went, or the side split changed: what draws them draws again. */
export function redraw(c: Controller, taskId?: string): void {
  c.presentations?.updateLayouts(taskId);
}

// --- intents -------------------------------------------------------------------

/** Shows a chat that a layout intent made or moved, and gives its prompt box the keyboard. Its
 * pane and its task's retained presentation are made ready first, so the center steps straight
 * from the task as it was to the task as it is, with the new pane sliding in, and never through
 * the fallback with a skeleton in that pane. A preparation that fails shows the chat all the same,
 * where its pane reports the failure. */
const show = Effect.fn("Chat.showMade")(function* (c: Controller, chat: Chat) {
  c.state.chats[chat.id] = chat;
  yield* c.prefetch(chat.id);
  yield* c.app.select(chat.id, chat.workspaceId);
  yield* c.views.focus(`prompt-${chat.id}`);
});

/** + in a pane's strip, or Cmd+T in the focused pane. */
export const newChatIn = Effect.fn("Chat.newChatIn")(function* (c: Controller, paneId: string) {
  const task = taskOnScreen(c);
  const made = yield* c.host.call("host/layouts.new_chat", { paneId, onScreen: task?.id ?? null });
  yield* show(c, made.chat);
});

/** A pane's split buttons, or Cmd+D and Cmd+Shift+D in the focused pane: a new chat in the new
 * half of a task's pane, and a New tab page in the new half of the side split's, which holds no
 * chat of the task's own. */
export const splitPane = Effect.fn("Chat.splitPane")(function* (c: Controller, paneId: string, direction: "right" | "down") {
  if (inSide(c, paneId)) return yield* openNewTab(c, paneId, direction);
  const task = taskOnScreen(c);
  const made = yield* c.host.call("host/layouts.split", { paneId, direction, onScreen: task?.id ?? null });
  yield* show(c, made.chat);
});

/** Selects the tab immediately; persisting its pane cannot change a later selection. */
export const showTab = Effect.fn("Chat.showTab")(function* (c: Controller, paneId: string, tab: Tab) {
  const task = taskOnScreen(c);
  c.state.layouts.sideFocused = inSide(c, paneId);
  const chatId = chatOf(tab);
  const chat = chatId ? c.state.chats[chatId] : undefined;
  if (chat) yield* c.app.select(chat.id, chat.workspaceId);
  yield* c.host.call("host/layouts.update", { paneId, active: tab, focused: true, onScreen: task?.id ?? null });
});

/** Focuses a pane the user clicked or typed in, and selects its chat in the sidebar. A pane's
 * view is drawn again only when it changes, so the task and pane it was drawn with may be old:
 * what is focused and shown now comes from the layouts as they are. */
export const focusPane = Effect.fn("Chat.focusPane")(function* (c: Controller, task: Task, pane: Pane) {
  const side = inSide(c, pane.id);
  const across = c.state.layouts.sideFocused !== side;
  c.state.layouts.sideFocused = side;
  const layout = side ? c.state.layouts.side?.layout : c.state.layouts.tasks[task.id]?.layout;
  const live = (layout && panesOf(layout.root).find((p) => p.id === pane.id)) ?? pane;
  const active = live.tabs.find((tab) => sameTab(tab, live.active)) ?? live.tabs[0];
  if (!active) return;
  const chatId = chatOf(active);
  if (!across && layout?.focused === pane.id && (!chatId || chatId === c.api.app.state().chatId)) return;
  yield* showTab(c, pane.id, active);
});

/** A tab's close button, a middle click, or Cmd+W on the focused pane's active tab. */
export const closeTab = Effect.fn("Chat.closeTab")(function* (c: Controller, tab: Tab, confirmed = false) {
  const task = taskOnScreen(c);
  // Chosen before the close: the host's event about the new layout comes later.
  const next = task && chatOf(tab) === c.api.app.state().chatId ? showAfterClosing(task, tab) : null;
  c.state.layouts.asking = null;
  const result = yield* c.host.call("host/layouts.close_tab", { tab, confirmed });
  // Its kind asks first (a file with unsaved changes): the question shows, and the tab stays.
  if (result.question) {
    c.state.layouts.asking = { tab, question: result.question };
    c.center?.update();
    return;
  }
  if (task && result.closed) {
    const kept = c.state.layouts.closed[task.id] ?? [];
    c.state.layouts.closed[task.id] = [result.closed, ...kept].slice(0, CLOSED_KEPT);
  }
  const chat = next ? c.state.chats[next] : undefined;
  if (chat) yield* c.app.select(chat.id, chat.workspaceId);
});

/** The chat on screen after a tab on screen closes: its right neighbour in the pane, else its
 * left one; with the pane's last tab, the active chat of the pane that takes its place. */
export function showAfterClosing(task: Task, tab: Tab): string | null {
  const panes = panesOf(task.layout.root);
  const pane = panes.find((p) => p.tabs.some((t) => sameTab(t, tab)));
  if (!pane) return null;
  const at = pane.tabs.findIndex((t) => sameTab(t, tab));
  const rest = pane.tabs.filter((t) => !sameTab(t, tab));
  const neighbour = rest[Math.min(at, rest.length - 1)];
  if (neighbour) return chatOf(neighbour);
  const other = panes.find((p) => p.id !== pane.id);
  return other ? chatOf(other.active) : null;
}

/** Cmd+Shift+T: the last closed chat of the task on screen goes back where it was. */
export const reopenTab = Effect.fn("Chat.reopenTab")(function* (c: Controller) {
  const task = taskOnScreen(c);
  if (!task) return;
  const closed = c.state.layouts.closed[task.id] ?? [];
  while (closed.length) {
    const last = closed.shift()!;
    const reopened = yield* c.host.call("host/layouts.reopen", { closed: last }).pipe(Effect.option);
    if (reopened._tag === "None") continue;
    const chat = c.state.chats[last.chatId];
    if (chat) yield* c.app.select(chat.id, chat.workspaceId);
    return;
  }
});

/** A drag on a split's handle ended: the shares it left. */
export const resizeSplit = Effect.fn("Chat.resizeSplit")(function* (c: Controller, splitId: string, shares: readonly number[]) {
  const task = taskOnScreen(c);
  yield* c.host.call("host/layouts.update", { shares: { splitId, shares }, onScreen: task?.id ?? null });
});

/** Cmd+Shift+B, or the side split's toggle: hides or shows it. */
export const toggleSideSplit = Effect.fn("Chat.toggleSideSplit")(function* (c: Controller) {
  // Settings has no side split to hide: a toggle there would change what
  // the chat shows when it comes back.
  if ((yield* c.app.state).route === "settings") return;
  const task = taskOnScreen(c);
  // Nothing to show for this task: the side split opens on a New tab page.
  if (task && !sideHasTabs(c.state.layouts, task, c.state.chats)) return yield* openNewTab(c);
  const open = !!c.state.layouts.side?.open;
  yield* c.host.call("host/layouts.update", { side: { open: !open }, onScreen: task?.id ?? null });
});

/** A drag on the side split's edge ended: the width it left, in pixels. */
export const resizeSide = Effect.fn("Chat.resizeSide")(function* (c: Controller, width: number) {
  yield* c.host.call("host/layouts.update", { side: { width: Math.round(width) }, onScreen: taskOnScreen(c)?.id ?? null });
});

/** A drop: a tab to a strip, an edge of a pane, another task, or a row of its own. */
export const placeTab = Effect.fn("Chat.placeTab")(function* (c: Controller, tab: Tab, target: PlaceTarget) {
  const task = taskOnScreen(c);
  yield* c.host.call("host/layouts.place", { tab, target, onScreen: task?.id ?? null });
  // A tab that lands in a pane is the tab that pane shows, and that pane has the focus (the host's rule). A chat's tab is
  // selected with it, so the focused pane's edge, the sidebar and the pane keys all agree on where it went.
  if (target.kind !== "strip" && target.kind !== "edge") return;
  c.state.layouts.sideFocused = inSide(c, target.paneId);
  const chatId = chatOf(tab);
  const chat = chatId ? c.state.chats[chatId] : undefined;
  if (chat) yield* show(c, chat);
});

/** The layout keys `when` reads (document 8) for a tab of the task on screen: the focused
 * pane's active tab when none is named. */
export function layoutKeys(c: Controller, tab?: Tab, paneId?: string) {
  const task = taskOnScreen(c);
  const side = c.state.layouts.side?.layout;
  const focused = task ? focusedPane(task) : null;
  const shown = tab ?? focused?.active;
  const inSide = !!side && !!(paneId ?? focused?.id) && panesOf(side.root).some((p) => p.id === (paneId ?? focused?.id));
  return {
    tabKind: !shown ? null : shown.kind === "chat" ? "chat" : shown.itemKind,
    tabInSideSplit: inSide,
    paneCount: task ? panesOf(task.layout.root).length : 0,
    taskOnScreen: !!task && chatCount(task) > 1,
  };
}

/** Tells the kernel the layout keys when they changed since the last report. */
export const reportLayoutKeys = Effect.fn("Chat.reportLayoutKeys")(function* (c: Controller) {
  const keys = layoutKeys(c);
  const json = JSON.stringify(keys);
  if (json === c.state.layouts.reported) return;
  c.state.layouts.reported = json;
  yield* c.kernel.call("context.layout", keys);
});

/** Opens a tab's menu at once with its own entries; the plugins' entries for it follow. */
export const openTabMenu = Effect.fn("Chat.openTabMenu")(function* (c: Controller, paneId: string, tab: Tab) {
  c.state.layouts.menu = { tab, paneId, entries: [] };
  c.titleView?.update();
  c.center?.update();
  // The list opens as a press on its trigger does, once the trigger is drawn.
  yield* c.views.focus("tab-menu");
  const { entries } = yield* c.kernel.call("menu.entries", { place: "tab", keys: layoutKeys(c, tab, paneId) });
  if (c.state.layouts.menu?.tab !== tab) return;
  c.state.layouts.menu = { tab, paneId, entries };
  c.titleView?.update();
  c.center?.update();
});

/** Close other tabs: every other tab of the pane closes; the first whose kind asks first shows
 * its question, and those tabs stay until the user answers. */
export const closeOtherTabs = Effect.fn("Chat.closeOtherTabs")(function* (c: Controller, paneId: string, keep: Tab) {
  const owners = [taskOnScreen(c)?.layout, c.state.layouts.side?.layout].filter((l) => !!l);
  const pane = owners.flatMap((l) => panesOf(l!.root)).find((p) => p.id === paneId);
  for (const tab of pane?.tabs ?? []) {
    if (sameTab(tab, keep)) continue;
    const result = yield* c.host.call("host/layouts.close_tab", { tab });
    if (result.closed) closeNoted(c, result.closed);
    if (result.question && !c.state.layouts.asking) c.state.layouts.asking = { tab, question: result.question };
  }
  if (c.state.layouts.asking) c.center?.update();
});

function closeNoted(c: Controller, closed: ClosedTab) {
  const task = taskOnScreen(c);
  if (!task) return;
  c.state.layouts.closed[task.id] = [closed, ...(c.state.layouts.closed[task.id] ?? [])].slice(0, CLOSED_KEPT);
}

/** Move to the side split, or into the task for a tab in it: the end of the other side's focused pane. */
export const moveAcross = Effect.fn("Chat.moveAcross")(function* (c: Controller, paneId: string, tab: Tab) {
  const task = taskOnScreen(c);
  const side = c.state.layouts.side?.layout;
  const inSide = !!side && panesOf(side.root).some((p) => p.id === paneId);
  const to = inSide ? (task ? focusedPane(task) : null) : side ? (panesOf(side.root).find((p) => p.id === side.focused) ?? null) : null;
  if (!to) return;
  yield* placeTab(c, tab, { kind: "strip", paneId: to.id, index: to.tabs.length });
});

/** Whether a chat tab of the task on screen can leave it for a row of its own: the task holds
 * another chat. */
export function separable(c: Controller, tab: Tab): boolean {
  const task = taskOnScreen(c);
  if (tab.kind !== "chat" || !task || c.state.layouts.homes[tab.chatId] !== task.id) return false;
  return tabsOf(task.layout.root).some((other) => other.kind === "chat" && other.chatId !== tab.chatId && c.state.layouts.homes[other.chatId] === task.id);
}

/** The tab menu's Separate from Task: the chat leaves its task for a row of its own. */
export const separateTab = Effect.fn("Chat.separateTab")(function* (c: Controller, tab: Tab) {
  yield* placeTab(c, tab, { kind: "alone" });
});

/** The panes the keyboard moves between: the task on screen's, and the side split's as it shows for that task. */
function keyboardPanes(c: Controller): { task: Task; side: Task | null; inSide: boolean } | null {
  const task = taskOnScreen(c);
  if (!task) return null;
  const side = sideOnScreen(c.state.layouts, task, c.state.chats)?.task ?? null;
  return { task, side, inSide: !!side && c.state.layouts.sideFocused };
}

/** Shows the next or previous tab of the focused pane, the side split's too (Cmd+Shift+] and Cmd+Shift+[). */
export const stepTab = Effect.fn("Chat.stepTab")(function* (c: Controller, by: 1 | -1) {
  const panes = keyboardPanes(c);
  const pane = panes ? focusedPane(panes.inSide ? panes.side! : panes.task) : null;
  if (!pane || pane.tabs.length < 2) return;
  const at = pane.tabs.findIndex((tab) => sameTab(tab, pane.active));
  yield* showTab(c, pane.id, pane.tabs[(at + by + pane.tabs.length) % pane.tabs.length]!);
});

/** Moves the keyboard to the neighbouring pane in a direction (Cmd+Option+Arrow): past the task's right edge into the
 * side split, and back out of its left edge. */
export const stepPane = Effect.fn("Chat.stepPane")(function* (c: Controller, toward: "left" | "right" | "up" | "down") {
  const panes = keyboardPanes(c);
  if (!panes) return;
  const here = panes.inSide ? panes.side! : panes.task;
  const target = neighbour(here.layout.root, here.layout.focused, toward);
  const across = !target && (panes.inSide ? toward === "left" : toward === "right" && panes.side) ? (panes.inSide ? panes.task : panes.side) : null;
  const pane = target ? panesOf(here.layout.root).find((p) => p.id === target) : across ? focusedPane(across) : undefined;
  if (pane) yield* focusPane(c, panes.task, pane);
});

/** The pane next to `from` in a direction, by the tree: the nearest split along that axis. */
export function neighbour(root: Layout, from: string, toward: "left" | "right" | "up" | "down"): string | null {
  const axis = toward === "left" || toward === "right" ? "row" : "column";
  const step = toward === "left" || toward === "up" ? -1 : 1;
  const path: { layout: Extract<Layout, { kind: "split" }>; index: number }[] = [];
  const find = (layout: Layout): boolean => {
    if (layout.kind === "pane") return layout.id === from;
    for (const [index, child] of layout.children.entries()) {
      path.push({ layout, index });
      if (find(child.layout)) return true;
      path.pop();
    }
    return false;
  };
  if (!find(root)) return null;
  for (let i = path.length - 1; i >= 0; i--) {
    const { layout, index } = path[i]!;
    if (layout.direction !== axis) continue;
    const next = layout.children[index + step];
    if (!next) continue;
    const panes = panesOf(next.layout);
    return (step > 0 ? panes[0] : panes.at(-1))?.id ?? null;
  }
  return null;
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.9latestNov 21, 2026>=5 <6349 KB5 permissionsListed
0.2.8Nov 16, 2026>=5 <6348.6 KB5 permissionsListed
0.2.7Nov 11, 2026>=5 <6314.3 KB5 permissionsListed
0.2.6Nov 9, 2026>=5 <6306.2 KB5 permissionsListed
0.2.5Oct 27, 2026>=2 <4178.6 KB5 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.