Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

34.7 KB
Raw Blame
/**
 * State of the dock system, as a tiny module-level store.
 *
 * The dock is TWO surfaces — one on the right edge, one at the bottom of the chat page —
 * and every side element is a TAB in one of them: the subagents panel, the Workspace
 * files panel, the Memory panel, the Trace panel, the messaging panel, the scheduled-tasks
 * panel, the built-in browser, and any number of terminals. A dock
 * shows its tabs in a strip and renders the active one; an OPEN dock with no tabs shows a
 * picker instead (choose what to open here), which is what the toolbar's two pull-open
 * buttons land on. Both docks can be open at once, and any tab can live in either dock
 * (the panel kinds are singletons — one tab per kind within a conversation — while
 * terminals are one tab per shell).
 *
 * The arrangement is SCOPED to the conversation it was made in, like each browser window
 * managing its own tabs: switching Sessions switches the whole arrangement, and no
 * conversation's tabs depend on another's. The shells behind terminal tabs are per-user
 * and keep running regardless; a scope only decides which of them are on screen here.
 * The draft page and pages with no Session use placeholder scopes; an arrangement made
 * while drafting is handed to the Session the first send creates (adoptDockScope).
 * Everything persists (one localStorage entry, least-recently-used scopes aging out), so
 * a reload restores each conversation's docks. Sizes are the exception: how wide/tall the
 * user likes a dock is one preference, not one per conversation.
 *
 * Closing a TAB removes it (the last tab closing also puts the dock away); a dock's ×
 * hides the surface, keeping its tabs — and, through closedDockView, everything their
 * bodies hold — for the next open. Below the desktop breakpoint the two docks render as ONE
 * merged bottom surface (a 320px-minimum right panel does not fit a phone); the stored
 * arrangement splits back apart when the window widens.
 *
 * The store knows panels by id alone. What an id names — its label, its mark, its body — is
 * the panel registry's (panel-registry.ts), so a tab whose panel this build has never heard of
 * (a plugin's, stored before the plugin loads) is kept as it is and rendered as a placeholder
 * until its definition arrives; only a key that cannot be a panel id at all is dropped.
 *
 * One surface at a time can be FULLSCREEN — the dock grown as far as its own edge goes: the right
 * dock over its row (the conversation beside it, with the toolbar above and the bottom dock below
 * still in view), the bottom dock or the narrow merged view up to the toolbar (over the row, and
 * the right dock in it). Fullscreen is remembered per arrangement in memory, never stored, so
 * switching away and back restores it; a reload or the breakpoint flipping clears it. It holds
 * while its surface is open with tabs and no dock it COVERS is brought forward (checked after every
 * mutation, in commit()): the right dock taking the stage under a fullscreen bottom dock drops
 * it, so what was asked for is seen rather than opening under the cover.
 *
 * A store (rather than component state) because the consumers live far apart: the chat
 * toolbar toggles the docks, the global hotkey flips the terminal, AppLayout points the
 * scope at the route's conversation, the chat page renders the docks, and the terminal
 * list prunes dead shells' tabs on refresh.
 */
import type { PanelId } from "./panel-registry";
import { DOCK_RATIO_MAX } from "./bottom-dock-size";

const LAYOUT_KEY = "penguin.dock.layout";
/** Scopes kept in storage; past that, the least recently touched conversations age out. */
const MAX_SCOPES = 40;

export type DockPosition = "right" | "bottom";

/**
 * Panels are singletons — one tab per id within a conversation — and terminals are the one
 * multi-instance tab kind. Which panels exist, and whether one is offered here (the built-in
 * browser exists only in the desktop app), is the registry's business; the store only carries
 * their ids.
 */
export type { PanelId };

export type DockTab = { kind: "panel"; panel: PanelId } | { kind: "terminal"; terminalId: string };

/** Stable identity of a tab ("agents", …, "terminal:<id>") — the stored form. */
export function tabKey(tab: DockTab): string {
  return tab.kind === "panel" ? tab.panel : `terminal:${tab.terminalId}`;
}

/**
 * The shape of a panel id: lowercase words joined by hyphens, with dots or slashes between
 * segments for a namespaced plugin panel ("acme.kanban", "acme/board"); the built-in ids all fit.
 * The store accepts any key of this shape without asking the registry, so a stored tab survives
 * its panel being unknown for a while.
 */
const PANEL_ID_PATTERN = /^[a-z][a-z0-9-]*(?:[./][a-z0-9-]+)*$/;
const PANEL_ID_MAX_LENGTH = 100;

export function isPanelId(key: string): boolean {
  return key.length <= PANEL_ID_MAX_LENGTH && PANEL_ID_PATTERN.test(key);
}

function parseTabKey(key: string): DockTab | null {
  if (key.startsWith("terminal:") && key.length > "terminal:".length)
    return { kind: "terminal", terminalId: key.slice("terminal:".length) };
  if (isPanelId(key)) return { kind: "panel", panel: key };
  return null;
}

/**
 * The bottom dock's HEIGHT is stored as a ratio of the chat page column; the height drawn from
 * it, clamped so the composer stays whole, is bottom-dock-size.ts's. The right dock's WIDTH is
 * not here: it is the shared side-panel width (use-panel-width.ts), unchanged from the pre-dock
 * panels.
 */
export const DEFAULT_DOCK_HEIGHT_RATIO = 0.4;
const DOCK_RATIO_MIN = 0.15;

function clampRatio(value: number): number {
  if (!Number.isFinite(value)) return DEFAULT_DOCK_HEIGHT_RATIO;
  return Math.min(DOCK_RATIO_MAX, Math.max(DOCK_RATIO_MIN, value));
}

interface DockAreaState {
  tabs: DockTab[];
  /** tabKey of the shown tab; kept pointing at a member (or null when empty). */
  active: string | null;
  /** An open dock is on screen — with tabs it shows the active one, without it shows the picker. */
  open: boolean;
}

function emptyArea(): DockAreaState {
  return { tabs: [], active: null, open: false };
}

/** One conversation's arrangement — everything setDockScope swaps. */
interface ScopeLayout {
  right: DockAreaState;
  bottom: DockAreaState;
  /** The dock touched last: the merged view's active tab follows it, and Ctrl+` targets it. */
  focus: DockPosition;
}

function emptyScope(): ScopeLayout {
  return { right: emptyArea(), bottom: emptyArea(), focus: "bottom" };
}

/**
 * The scope the dock belongs to before any conversation is open — the login screen, a
 * settings page reached directly by URL. A real Session id never collides with it. The
 * draft page instead scopes to its route id ("new" / a parked draft id), whose
 * arrangement adoptDockScope hands to the Session the first send creates.
 */
const NO_SCOPE = "~none";

function readJson<T>(key: string, fallback: T): T {
  try {
    const raw = localStorage.getItem(key);
    if (raw === null) return fallback;
    const parsed: unknown = JSON.parse(raw);
    return typeof parsed === "object" && parsed !== null ? (parsed as T) : fallback;
  } catch {
    return fallback; // node env / private mode / malformed entry: start from the default
  }
}

function writeJson(key: string, value: unknown): void {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch {
    // Private-mode storage failures only cost persistence.
  }
}

/**
 * One stored dock, made safe to use. Storage is user-writable and survives across
 * versions, so a malformed entry has to degrade to an empty dock — this runs at module
 * load, where a throw would take the whole app down with it.
 */
function sanitizeArea(raw: unknown): DockAreaState {
  const area = (raw ?? {}) as Partial<{ tabs: unknown; active: unknown; open: unknown }>;
  const tabs = (Array.isArray(area.tabs) ? area.tabs : [])
    .map((key) => (typeof key === "string" ? parseTabKey(key) : null))
    .filter((tab): tab is DockTab => tab !== null);
  // One tab per key: a duplicated stored entry would render two strips fighting over one active.
  const seen = new Set<string>();
  const unique = tabs.filter((tab) => {
    const key = tabKey(tab);
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
  const active =
    typeof area.active === "string" && unique.some((tab) => tabKey(tab) === area.active)
      ? area.active
      : unique.length > 0
        ? tabKey(unique[unique.length - 1]!)
        : null;
  return { tabs: unique, active, open: area.open === true };
}

function sanitizeScope(raw: unknown): ScopeLayout {
  const scope = (raw ?? {}) as Partial<Record<string, unknown>>;
  const right = sanitizeArea(scope.right);
  const bottom = sanitizeArea(scope.bottom);
  // A panel key present in both docks keeps the right copy (sanitizeArea dedupes only within a dock).
  const rightKeys = new Set(right.tabs.map(tabKey));
  bottom.tabs = bottom.tabs.filter((tab) => !rightKeys.has(tabKey(tab)));
  if (bottom.active !== null && !bottom.tabs.some((tab) => tabKey(tab) === bottom.active))
    bottom.active = bottom.tabs.length > 0 ? tabKey(bottom.tabs[bottom.tabs.length - 1]!) : null;
  return { right, bottom, focus: scope.focus === "right" ? "right" : "bottom" };
}

interface StoredLayout {
  scopes: Record<string, unknown>;
  bottomRatio: unknown;
}

function loadStored(): { scopes: Record<string, ScopeLayout>; bottomRatio: number } {
  const raw = readJson<Partial<StoredLayout>>(LAYOUT_KEY, {});
  const scopes: Record<string, ScopeLayout> = {};
  if (typeof raw.scopes === "object" && raw.scopes !== null) {
    for (const [key, value] of Object.entries(raw.scopes)) scopes[key] = sanitizeScope(value);
  }
  return {
    scopes,
    bottomRatio: clampRatio(typeof raw.bottomRatio === "number" ? raw.bottomRatio : NaN),
  };
}

let { scopes, bottomRatio: ratio } = loadStored();
let scope = NO_SCOPE;
// Unpacked into a local rather than read through `scopes[scope]` everywhere: the reads
// are on every render path, and one live object per scope keeps switching cheap.
let layout: ScopeLayout = scopes[scope] ?? emptyScope();
/**
 * Fullscreen follows the arrangement, including a draft handed to its new Session. Weak keys
 * let evicted scopes go without a second retention list; the storage format stays unchanged.
 * A reload or breakpoint flip starts every arrangement in the normal layout.
 */
let fullscreenByLayout = new WeakMap<ScopeLayout, DockPosition>();

/** Whether a scope's arrangement is worth a storage entry at all. */
function scopeIsEmpty(s: ScopeLayout): boolean {
  return s.right.tabs.length === 0 && s.bottom.tabs.length === 0 && !s.right.open && !s.bottom.open;
}

/** Writes the live layout back into the scope map and persists it. */
function persist(): void {
  // An untouched scope is not worth a storage entry: visiting a conversation without ever
  // opening a dock would otherwise leave one behind for every conversation visited.
  if (scopeIsEmpty(layout)) {
    const { [scope]: _dropped, ...rest } = scopes;
    scopes = rest;
  } else {
    // Re-inserted last so key order is least-recently-touched first, which is what the cap
    // below evicts by.
    const { [scope]: _previous, ...rest } = scopes;
    scopes = { ...rest, [scope]: layout };
  }
  const keys = Object.keys(scopes);
  if (keys.length > MAX_SCOPES) {
    scopes = Object.fromEntries(keys.slice(keys.length - MAX_SCOPES).map((k) => [k, scopes[k]!]));
  }
  writeScopes();
}

/**
 * Writes the scope map as it stands. Kept apart from `persist` because a handoff moves the map
 * itself: writing the live layout then would put the arrangement back under the key it left.
 */
function writeScopes(): void {
  writeJson(LAYOUT_KEY, {
    scopes: Object.fromEntries(
      Object.entries(scopes).map(([key, s]) => [
        key,
        {
          right: { ...s.right, tabs: s.right.tabs.map(tabKey) },
          bottom: { ...s.bottom, tabs: s.bottom.tabs.map(tabKey) },
          focus: s.focus,
        },
      ]),
    ),
    bottomRatio: ratio,
  });
}

const listeners = new Set<() => void>();
let version = 0;
let instant = 0;

function notify(): void {
  version += 1;
  for (const listener of [...listeners]) listener();
}

/**
 * The tail of every mutation: the layout reaches storage, the fullscreen state is checked
 * against what the mutation left on screen, and the listeners hear about it. One place, so no
 * action has to remember the check — a new action that ends in commit() is covered.
 */
function commit(): void {
  persist();
  reconcileFullscreen();
  notify();
}

/** Monotonic change counter — subscribe with this snapshot to re-render on ANY change. */
export function dockVersion(): number {
  return version;
}

/**
 * Counter of changes that must NOT animate: scope switches (a context swap, not a
 * collapse gesture) and cross-dock moves (the tab jumps to the other edge — animating
 * the source's collapse and the target's expansion would read as two motions for one
 * action). The renderer compares it across updates: bumped together with the change ⇒
 * apply the new layout instantly; otherwise play the expand/collapse transition.
 */
export function instantVersion(): number {
  return instant;
}

export function subscribeDock(listener: () => void): () => void {
  listeners.add(listener);
  return () => listeners.delete(listener);
}

// -------------------------------------------------------------------------------- scope

/**
 * Points the dock at a conversation (or a placeholder off one). Everything on screen
 * changes with it; the shells behind terminal tabs are untouched, so switching away and
 * back costs nothing. A dock arranged before a conversation was chosen (the `~none`
 * placeholder — /chat resolves to a Session a moment after it loads) is handed to the
 * conversation that is chosen, never clobbering one that has an arrangement of its own.
 */
export function setDockScope(next: string | null): void {
  switchScope(next ?? NO_SCOPE, scope === NO_SCOPE);
}

/**
 * The draft `from` has become a real Session (or a Session's id self-healed into a new one):
 * its arrangement moves to the new id, never clobbering one the new id already has. Called at
 * the points that turn a draft into a Session (its send paths, and a self-heal renaming a
 * session id), not on any navigation away from the draft.
 *
 * Those points come after network round trips, and the person may have moved on meanwhile. True
 * when they are still on `from` — its docks are the ones on screen, and `stillOpen` (the page
 * that asked is still mounted) says it is the same page, not a new draft of the same Project
 * reusing the scope: the docks follow to the new id, and the caller takes the route there too.
 * False otherwise: the person stays where they are, the docks on screen are left alone, and
 * `from`'s stored arrangement moves to the new id unless the page on screen is using it.
 */
export function adoptDockScope(from: string, sessionId: string, stillOpen = true): boolean {
  if (from === scope) {
    if (!stillOpen) return false;
    switchScope(sessionId, true);
    return true;
  }
  const staged = scopes[from];
  if (from === sessionId || staged === undefined || scopes[sessionId] !== undefined) return false;
  const { [from]: _moved, ...rest } = scopes;
  scopes = { ...rest, [sessionId]: staged };
  writeScopes();
  // Already on the new id, with nothing arranged there yet: what moved is what it shows.
  if (sessionId === scope) {
    layout = staged;
    reconcileFullscreen();
    notify();
  }
  return false;
}

function switchScope(target: string, mayHandOver: boolean): void {
  if (target === scope) return;
  instant += 1;
  persist();
  const staged = scopes[scope];
  // Never clobbers: a target with an arrangement of its own keeps it.
  const handedOver = mayHandOver && staged !== undefined && scopes[target] === undefined;
  if (handedOver) {
    const { [scope]: _moved, ...rest } = scopes;
    scopes = { ...rest, [target]: staged };
    // The move has to reach storage here. persist() above wrote the map under the OLD
    // key; leaving it at that means a reload reads the arrangement back under a key
    // nothing routes to — and, for a draft, hands it to the next draft instead.
    writeScopes();
  }
  scope = target;
  layout = scopes[scope] ?? emptyScope();
  // An inactive scope may have lost its last terminal while another Session was on screen.
  reconcileFullscreen();
  notify();
}

/** The scope on screen (tests and diagnostics; components never need it). */
export function currentDockScope(): string {
  return scope;
}

/**
 * Whether a page with docks is on screen. Pages without them (organization pages, login, the
 * standalone /terminal page) sit on the `~none` placeholder, where a dock command would act on
 * nothing visible — or worse, spawn shells into an arrangement the next conversation inherits.
 */
export function docksOnScreen(): boolean {
  return scope !== NO_SCOPE;
}

// ------------------------------------------------------------------------------- narrow

/**
 * Below 1024px (the breakpoint the pre-dock panels used) the docks merge into one bottom
 * surface. The store owns the media query so every narrow-aware decision (merged active,
 * toggle semantics, the view models) lives in one place; components just render dockViews().
 */
let narrow = false;
if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
  const query = window.matchMedia("(max-width: 1023.98px)");
  narrow = query.matches;
  query.addEventListener("change", (event) => {
    narrow = event.matches;
    // The surfaces are re-cut at the breakpoint (two docks ↔ one merged view), so the surface
    // that was fullscreen no longer exists as such; the user re-enters on the new one if wanted.
    fullscreenByLayout = new WeakMap();
    notify();
  });
}

export function isNarrow(): boolean {
  return narrow;
}

// ------------------------------------------------------------------------------ getters

function area(position: DockPosition): DockAreaState {
  return layout[position];
}

function findTab(key: string): { position: DockPosition; index: number } | null {
  for (const position of ["right", "bottom"] as const) {
    const index = layout[position].tabs.findIndex((tab) => tabKey(tab) === key);
    if (index !== -1) return { position, index };
  }
  return null;
}

/** The dock a tab lives in (open or not), or null when no dock holds it. */
export function tabHome(key: string): DockPosition | null {
  return findTab(key)?.position ?? null;
}

/** Whether a dock occupies its edge. An open dock with no tabs shows the picker. */
export function isDockVisible(position: DockPosition): boolean {
  return area(position).open;
}

export function dockTabs(position: DockPosition): DockTab[] {
  return area(position).tabs;
}

export function dockActiveKey(position: DockPosition): string | null {
  return area(position).active;
}

/** Whether a dock has anything to show at all — the closed merged view's counterpart to visibility. */
function hasTabs(position: DockPosition): boolean {
  return area(position).tabs.length > 0;
}

/**
 * The merged view's active tab: the focused dock's active when that dock counts, else the
 * other's. What "the shown tab" means below the breakpoint. `counts` is what being on
 * screen means for the view being built — visibility for the merged view the docks render,
 * having tabs at all for the closed one that only keeps its panels mounted.
 */
function mergedActiveKey(counts: (position: DockPosition) => boolean): string | null {
  const first = layout.focus;
  const second: DockPosition = first === "right" ? "bottom" : "right";
  if (counts(first) && area(first).active !== null) return area(first).active;
  if (counts(second)) return area(second).active;
  return null;
}

/** One renderable dock: where it sits, what its strip lists, which tab shows. */
export interface DockView {
  position: DockPosition;
  /** True for the narrow merged view (its strip spans both docks; its × hides both). */
  merged: boolean;
  tabs: DockTab[];
  activeKey: string | null;
}

/**
 * The docks to render right now. Wide: one view per open dock. Narrow: a single merged
 * bottom view listing every open dock's tabs (bottom's first — it is the surface the
 * merged view inherits). An open dock with no tabs renders its picker.
 */
export function dockViews(): DockView[] {
  if (!narrow) {
    return (["right", "bottom"] as const).filter(isDockVisible).map((position) => ({
      position,
      merged: false,
      tabs: area(position).tabs,
      activeKey: area(position).active,
    }));
  }
  if (!isDockVisible("right") && !isDockVisible("bottom")) return [];
  const tabs = [
    ...(isDockVisible("bottom") ? layout.bottom.tabs : []),
    ...(isDockVisible("right") ? layout.right.tabs : []),
  ];
  return [{ position: "bottom", merged: true, tabs, activeKey: mergedActiveKey(isDockVisible) }];
}

/**
 * The view a CLOSED dock would render if it opened. The chat page keeps a collapsed dock's
 * node mounted on this, so hiding costs no panel state: the file preview, the editor draft
 * and the shell on screen are all still there on the way back. Null when there is nothing
 * to keep — the dock is open (dockViews() lists it then), it has no tabs, or it is the
 * narrow layout's right dock, whose tabs the merged bottom view carries.
 */
export function closedDockView(position: DockPosition): DockView | null {
  if (narrow) {
    if (position === "right" || isDockVisible("right") || isDockVisible("bottom")) return null;
    const tabs = [...layout.bottom.tabs, ...layout.right.tabs];
    if (tabs.length === 0) return null;
    return { position: "bottom", merged: true, tabs, activeKey: mergedActiveKey(hasTabs) };
  }
  if (isDockVisible(position) || !hasTabs(position)) return null;
  return { position, merged: false, tabs: area(position).tabs, activeKey: area(position).active };
}

/** Whether a tab is the one actually on screen (narrow-aware — what a toggle closes). */
export function isTabShown(key: string): boolean {
  const home = tabHome(key);
  if (home === null || !isDockVisible(home)) return false;
  return narrow ? mergedActiveKey(isDockVisible) === key : area(home).active === key;
}

/** Whether a tab sits in a visible dock at all (shown or behind another tab). */
export function isTabOnScreen(key: string): boolean {
  const home = tabHome(key);
  return home !== null && isDockVisible(home);
}

// ------------------------------------------------------------------------------ actions

function activate(position: DockPosition, key: string): void {
  const state = area(position);
  state.active = key;
  state.open = true;
  layout.focus = position;
}

/** Brings an existing tab on screen: opens its dock, makes it active, focuses its dock. */
export function activateTab(key: string): void {
  const found = findTab(key);
  if (!found) return;
  activate(found.position, key);
  commit();
}

function insertTab(tab: DockTab, position: DockPosition): void {
  const key = tabKey(tab);
  const existing = findTab(key);
  if (existing && existing.position !== position) {
    layout[existing.position].tabs = layout[existing.position].tabs.filter(
      (t) => tabKey(t) !== key,
    );
    if (layout[existing.position].active === key) {
      const rest = layout[existing.position].tabs;
      layout[existing.position].active = rest.length > 0 ? tabKey(rest[rest.length - 1]!) : null;
    }
  }
  if (!existing || existing.position !== position) {
    layout[position].tabs = [...layout[position].tabs, tab];
  }
  activate(position, key);
}

/**
 * Removes a tab wherever it lives; the dock falls back to its last remaining tab, and
 * removing the LAST tab puts the dock away — from the user's seat the × closed the
 * content, so no empty surface (nor a surprise picker) should linger.
 */
export function removeTab(key: string): void {
  const found = findTab(key);
  if (!found) return;
  const state = area(found.position);
  state.tabs = state.tabs.filter((tab) => tabKey(tab) !== key);
  if (state.active === key)
    state.active = state.tabs.length > 0 ? tabKey(state.tabs[state.tabs.length - 1]!) : null;
  if (state.tabs.length === 0) state.open = false;
  commit();
}

/** Moves one tab to the other dock (drag / the dock pickers), activating it there. */
export function moveTab(key: string, to: DockPosition): void {
  const found = findTab(key);
  if (!found) return;
  instant += 1;
  const tab = layout[found.position].tabs[found.index]!;
  insertTab(tab, to);
  if (layout[found.position].tabs.length === 0) layout[found.position].open = false;
  commit();
}

/** Moves a whole dock's tabs onto the other edge, after any tabs already there. */
export function moveDock(from: DockPosition, to: DockPosition): void {
  if (from === to) return;
  const source = area(from);
  if (source.tabs.length === 0) return;
  instant += 1;
  const shown = source.active;
  const target = area(to);
  target.tabs = [...target.tabs, ...source.tabs];
  source.tabs = [];
  source.active = null;
  source.open = false;
  if (shown !== null) activate(to, shown);
  else layout.focus = to;
  target.open = true;
  commit();
}

/** Reorders one dock's strip; `keys` is the full new order of that dock's tabs. */
export function reorderDock(position: DockPosition, keys: readonly string[]): void {
  const state = area(position);
  const byKey = new Map(state.tabs.map((tab) => [tabKey(tab), tab]));
  const next = keys.map((key) => byKey.get(key)).filter((tab): tab is DockTab => tab !== undefined);
  if (next.length !== state.tabs.length) return; // a stale drag; keep the strip consistent
  if (next.every((tab, index) => tab === state.tabs[index])) return;
  state.tabs = next;
  commit();
}

/**
 * The toolbar's two pull-open buttons: an open dock goes away (its tabs stay for the next
 * open); a closed one comes on screen — showing its tabs, or the picker when it has none.
 */
export function toggleDock(position: DockPosition): void {
  const state = area(position);
  state.open = !state.open;
  if (state.open) layout.focus = position;
  commit();
}

/** The merged view's ×: both docks away (wide views pass their own position instead). */
export function hideView(view: DockView): void {
  if (view.merged) {
    layout.right.open = false;
    layout.bottom.open = false;
  } else {
    area(view.position).open = false;
  }
  commit();
}

// --------------------------------------------------------------------------- fullscreen

/** The surface grown to its fullscreen cover ("bottom" for the narrow merged view), or null. */
export function fullscreenDock(): DockPosition | null {
  return fullscreenByLayout.get(layout) ?? null;
}

/** Whether the merged view is on screen with something in its strip (rather than its picker). */
function mergedViewHasTabs(candidate: ScopeLayout): boolean {
  return (
    (candidate.bottom.open && candidate.bottom.tabs.length > 0) ||
    (candidate.right.open && candidate.right.tabs.length > 0)
  );
}

/**
 * Whether a surface can be fullscreen as the layout stands: on screen with tabs (the picker is
 * never fullscreen). Wide, the surface is one dock; narrow, it is the merged view, which only
 * exists at the bottom.
 */
function fullscreenEligible(position: DockPosition, candidate: ScopeLayout = layout): boolean {
  if (narrow) return position === "bottom" && mergedViewHasTabs(candidate);
  return candidate[position].open && candidate[position].tabs.length > 0;
}

/**
 * Drops fullscreen when its surface stopped qualifying — hidden, or its last tab gone — and when a
 * dock it COVERS takes the stage, which would otherwise happen invisibly under the cover. Only the
 * bottom dock's cover reaches another dock: it climbs to the toolbar, over the right dock, so the
 * right dock being touched — activated, opened, or had something moved into it — ends it. The
 * right dock's cover is its own row, with the bottom dock still in view below it, so the bottom
 * dock opening, being touched or receiving a tab leaves it alone; so does anything within the
 * merged view, which is every dock there is. Runs in commit(), after every mutation.
 */
function reconcileFullscreen(candidate: ScopeLayout = layout): void {
  const fullscreen = fullscreenByLayout.get(candidate) ?? null;
  if (fullscreen === null) return;
  const coveredTakesStage = !narrow && fullscreen === "bottom" && candidate.focus === "right";
  if (!fullscreenEligible(fullscreen, candidate) || coveredTakesStage)
    fullscreenByLayout.delete(candidate);
}

/**
 * Enters (a position) or leaves (null). Entering counts as touching that dock — it becomes the
 * focused one, so the header button works on a dock that was not touched last — and is a no-op
 * for a surface that is not on screen with tabs.
 */
export function setDockFullscreen(position: DockPosition | null): void {
  if (position !== null && !fullscreenEligible(position)) return;
  if (position !== null && !narrow && layout.focus !== position) {
    layout.focus = position;
    persist();
  }
  if (position === fullscreenDock()) return;
  if (position === null) fullscreenByLayout.delete(layout);
  else fullscreenByLayout.set(layout, position);
  notify();
}

// ------------------------------------------------------------------------------- panels

/** The dock a panel's tab lives in (open or not), or null when the panel is closed. */
export function panelDock(id: PanelId): DockPosition | null {
  return tabHome(id);
}

/**
 * Puts a panel on screen: adds its tab (to `position`, or where it already lives, or the
 * right dock — the default edge for panels opened from the conversation) and activates
 * it. Idempotent when already shown.
 */
export function openPanel(id: PanelId, position?: DockPosition): void {
  const target = position ?? panelDock(id) ?? "right";
  insertTab({ kind: "panel", panel: id }, target);
  commit();
}

export function closePanel(id: PanelId): void {
  removeTab(id);
}

// ---------------------------------------------------------------------------- terminals

function terminalKey(id: string): string {
  return `terminal:${id}`;
}

/** The dock a terminal's tab lives in within THIS scope, or null when it has no tab here. */
export function terminalTabDock(id: string): DockPosition | null {
  return tabHome(terminalKey(id));
}

/** This scope's terminal tabs, in strip order (bottom dock first). */
export function terminalTabIds(): string[] {
  return [...layout.bottom.tabs, ...layout.right.tabs]
    .filter((tab): tab is Extract<DockTab, { kind: "terminal" }> => tab.kind === "terminal")
    .map((tab) => tab.terminalId);
}

/**
 * Of `ids`, the ones no conversation holds — created through the API or the CLI, or whose
 * tab was closed. A dock picker's terminal row adopts one of these rather than spawning a
 * second shell beside a perfectly good one.
 */
export function unownedTerminals(ids: readonly string[]): string[] {
  const owned = new Set<string>();
  for (const s of [layout, ...Object.values(scopes)]) {
    for (const tab of [...s.right.tabs, ...s.bottom.tabs]) {
      if (tab.kind === "terminal") owned.add(tab.terminalId);
    }
  }
  return ids.filter((id) => !owned.has(id));
}

/** New terminals land at the bottom dock unless a dock asked for them explicitly. */
export function addTerminalTab(id: string, position?: DockPosition): void {
  insertTab({ kind: "terminal", terminalId: id }, position ?? terminalTabDock(id) ?? "bottom");
  commit();
}

/**
 * Brings a terminal on screen in this conversation: its tab activates where it lives, or
 * a new tab joins the bottom dock.
 */
export function showTerminal(id: string): void {
  addTerminalTab(id);
}

/**
 * Puts a terminal tab back into a NAMED conversation's dock — the detach round trip: the
 * tab left scope X when its shell moved to a window, and closing that window must return
 * it to X even when another conversation is on screen by then. No-op when any scope
 * already holds the shell (the user re-tabbed it meanwhile).
 */
export function restoreTerminalTab(scopeId: string, id: string, position: DockPosition): void {
  if (unownedTerminals([id]).length === 0) return;
  if (scopeId === scope) {
    addTerminalTab(id, position);
    return;
  }
  const target = scopes[scopeId] ?? emptyScope();
  const state = target[position];
  state.tabs = [...state.tabs, { kind: "terminal", terminalId: id }];
  state.active = terminalKey(id);
  state.open = true;
  const { [scopeId]: _previous, ...rest } = scopes;
  scopes = { ...rest, [scopeId]: target };
  commit();
}

/**
 * Drops tabs of terminals that no longer exist — across every scope, not just the one on
 * screen: a dead shell's id would otherwise sit in an inactive conversation's arrangement
 * until that conversation aged out of storage.
 */
export function pruneTerminalTabs(liveIds: ReadonlySet<string>): void {
  let changed = false;
  const pruneArea = (state: DockAreaState): boolean => {
    const kept = state.tabs.filter((tab) => tab.kind !== "terminal" || liveIds.has(tab.terminalId));
    if (kept.length === state.tabs.length) return false;
    state.tabs = kept;
    if (state.active !== null && !kept.some((tab) => tabKey(tab) === state.active))
      state.active = kept.length > 0 ? tabKey(kept[kept.length - 1]!) : null;
    if (kept.length === 0) state.open = false;
    return true;
  };
  for (const s of Object.values(scopes)) {
    if (s === layout) continue; // the live scope is pruned below
    if (pruneArea(s.right)) changed = true;
    if (pruneArea(s.bottom)) changed = true;
    reconcileFullscreen(s);
  }
  if (pruneArea(layout.right)) changed = true;
  if (pruneArea(layout.bottom)) changed = true;
  if (!changed) return;
  commit();
}

/**
 * Ctrl+`'s toggle, on the store's synchronous half: hides the docks that hold this
 * conversation's terminal tabs when one is shown; restores/activates the newest terminal
 * tab when there are tabs but none on screen. Returns false when this scope has no
 * terminal tab at all — the caller (dock-terminal.ts) then adopts or creates a shell,
 * which is async.
 */
export function toggleTerminalDocks(): boolean {
  const ids = terminalTabIds();
  if (ids.length === 0) return false;
  const holders = (["right", "bottom"] as const).filter((position) =>
    area(position).tabs.some((tab) => tab.kind === "terminal"),
  );
  const anyShown = holders.some(
    (position) =>
      isDockVisible(position) &&
      (narrow
        ? mergedActiveKey(isDockVisible)?.startsWith("terminal:") === true
        : area(position).active?.startsWith("terminal:") === true),
  );
  if (anyShown) {
    for (const position of holders) area(position).open = false;
    commit();
    return true;
  }
  showTerminal(ids[ids.length - 1]!);
  return true;
}

// -------------------------------------------------------------------------------- sizes

/** The bottom dock's height, as a ratio of the chat page column (a global preference). */
export function bottomRatio(): number {
  return ratio;
}

export function setBottomRatio(next: number): void {
  const clamped = clampRatio(next);
  if (clamped === ratio) return;
  ratio = clamped;
  commit();
}

export function resetBottomRatio(): void {
  ratio = DEFAULT_DOCK_HEIGHT_RATIO;
  commit();
}