diff --git a/web/src/connections.ts b/web/src/connections.ts index 5bf948f..ac72ada 100644 --- a/web/src/connections.ts +++ b/web/src/connections.ts @@ -6,29 +6,43 @@ import { import type { Uuid } from "./types.js"; /** - * How many live attach connections to keep buffering in the background. The - * most-recently-viewed sessions stay connected so switching back to them is - * instant; older ones are evicted (their WS closed) once the cap is exceeded. - * Bounded so the browser doesn't hold an unbounded fan of open sockets. + * How many *parked* (off-screen but still-connected) sessions to keep warm + * beyond whatever is currently visible. Visible panes are never counted or + * evicted — only this background buffer is bounded, so the browser doesn't hold + * an unbounded fan of open sockets. Switching back to a recently-viewed session + * is instant while it's still parked; older ones are evicted (WS closed) once + * the buffer overflows. */ -const MAX_LIVE = 6; +const MAX_PARKED = 6; + +export interface PoolOptions { + /** Fired when the focused session changes (drives sidebar highlight + HUD). */ + onFocusChange?: (id: Uuid | null) => void; + /** Fired when a view's explicit disconnect control is used; the embedder + * decides how to update the layout/route (then typically calls `close`). */ + onRequestClose?: (id: Uuid) => void; +} /** - * Owns the set of live attach connections, decoupled from the router/UI. The - * shell asks the pool to `activate(id, pane)` on navigation; the pool mounts - * that session's view and parks the previously-active one in a hidden cache — - * still connected. Connections only die on eviction, explicit `close`, or the - * caller disposing the pool. + * Owns the set of live attach connections, decoupled from the router/UI. + * + * Unlike the old single-active pool, several connections can be **mounted** + * (visible) at once — one per leaf of the active tab's layout tree. The shell + * reconciles the visible set with {@link setVisible}; sessions no longer shown + * are **parked** in a hidden cache (still streaming) and bounded by an LRU. A + * connection only dies on eviction, an explicit {@link close}, or {@link dispose}. */ export class ConnectionPool { - /** Insertion order doubles as LRU: oldest key first, newest (active) last. */ + /** All live connections. Insertion order doubles as LRU: oldest first. */ private readonly cache = new Map(); + /** Sessions currently mounted into a visible pane (never evicted). */ + private readonly mounted = new Set(); private readonly hidden: HTMLElement; - private activeId: Uuid | null = null; - private onActiveChange?: (id: Uuid | null) => void; + private focusedId: Uuid | null = null; + private readonly opts: PoolOptions; - constructor(opts: { onActiveChange?: (id: Uuid | null) => void } = {}) { - this.onActiveChange = opts.onActiveChange; + constructor(opts: PoolOptions = {}) { + this.opts = opts; // Off-screen home for parked, still-connected terminals. this.hidden = document.createElement("div"); this.hidden.className = "conn-cache"; @@ -36,92 +50,116 @@ export class ConnectionPool { document.body.appendChild(this.hidden); } - /** Currently-mounted session, or null when showing the welcome pane. */ + /** The focused session, or null when nothing is focused (welcome pane). */ + focused(): Uuid | null { + return this.focusedId; + } + + /** Back-compat alias for {@link focused} (used by the debug HUD). */ active(): Uuid | null { - return this.activeId; + return this.focusedId; + } + + isMounted(id: Uuid): boolean { + return this.mounted.has(id); } /** - * Show `id` in `pane`, reusing its live connection if one exists. The - * previously-active view is parked (kept connected) in the hidden cache. + * Ensure `id` is live and shown inside `pane`, reusing its connection if one + * exists (refreshing LRU recency). Does not touch other mounted panes. */ - activate(id: Uuid, pane: HTMLElement, info?: AttachInfo): void { - if (this.activeId && this.activeId !== id) this.park(this.activeId); - + mount(id: Uuid, pane: HTMLElement, info?: AttachInfo): void { let conn = this.cache.get(id); if (conn) { - // Refresh LRU recency. this.cache.delete(id); this.cache.set(id, conn); } else { conn = createAttachConnection( id, - { onRequestClose: (sid) => this.requestClose(sid) }, + { onRequestClose: (sid) => this.opts.onRequestClose?.(sid) }, info, ); this.cache.set(id, conn); - this.evict(id); } - - pane.replaceChildren(conn.el); - conn.onMount(); - this.activeId = id; - this.onActiveChange?.(id); + if (conn.el.parentElement !== pane) { + pane.replaceChildren(conn.el); + conn.onMount(); + } else if (!this.mounted.has(id)) { + conn.onMount(); + } + this.mounted.add(id); + this.evict(); } - /** Detach the active view back to the cache (still connected) — e.g. when - * navigating to the welcome pane. */ - parkActive(): void { - if (this.activeId) { - this.park(this.activeId); - this.activeId = null; - this.onActiveChange?.(null); + /** Park `id` back into the hidden cache (still connected) and stop showing it. */ + unmount(id: Uuid): void { + if (!this.mounted.delete(id)) return; + const conn = this.cache.get(id); + if (conn) { + this.hidden.appendChild(conn.el); // stays alive, just off-screen + conn.onUnmount(); } } + /** + * Reconcile the visible set to exactly `entries` (in render order): park any + * mounted session not listed, mount/refresh each listed one in its pane. + */ + setVisible(entries: { id: Uuid; pane: HTMLElement; info?: AttachInfo }[]): void { + const next = new Set(entries.map((e) => e.id)); + for (const id of [...this.mounted]) { + if (!next.has(id)) this.unmount(id); + } + for (const e of entries) this.mount(e.id, e.pane, e.info); + } + + setFocus(id: Uuid | null): void { + if (id === this.focusedId) return; + this.focusedId = id; + this.opts.onFocusChange?.(id); + } + + /** Compat shim: show `id` alone in `pane` and focus it; park everything else. */ + activate(id: Uuid, pane: HTMLElement, info?: AttachInfo): void { + this.setVisible([{ id, pane, info }]); + this.setFocus(id); + } + + /** Compat shim: park all visible panes and clear focus (e.g. welcome pane). */ + parkActive(): void { + for (const id of [...this.mounted]) this.unmount(id); + this.setFocus(null); + } + /** Fully disconnect + forget a session. */ close(id: Uuid): void { const conn = this.cache.get(id); if (!conn) return; conn.dispose(); this.cache.delete(id); - if (this.activeId === id) { - this.activeId = null; - this.onActiveChange?.(null); - } + this.mounted.delete(id); + if (this.focusedId === id) this.setFocus(null); } dispose(): void { for (const conn of this.cache.values()) conn.dispose(); this.cache.clear(); + this.mounted.clear(); this.hidden.remove(); } - private park(id: Uuid): void { - const conn = this.cache.get(id); - if (!conn) return; - this.hidden.appendChild(conn.el); // stays alive, just off-screen - conn.onUnmount(); - } - - /** Drop least-recently-viewed connections beyond the cap (never `keep`). */ - private evict(keep: Uuid): void { - while (this.cache.size > MAX_LIVE) { + /** Drop least-recently-viewed *parked* connections beyond the buffer cap. */ + private evict(): void { + while (this.cache.size - this.mounted.size > MAX_PARKED) { let victim: Uuid | null = null; for (const id of this.cache.keys()) { - if (id !== keep && id !== this.activeId) { + if (!this.mounted.has(id)) { victim = id; break; } } - if (!victim) break; + if (victim === null) break; this.close(victim); } } - - private requestClose(id: Uuid): void { - this.close(id); - // Drop back to the welcome pane via the router. - if (location.hash !== "#/" && location.hash !== "") location.hash = "#/"; - } } diff --git a/web/src/main.ts b/web/src/main.ts index bb491f9..218e85a 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -3,6 +3,15 @@ import { ConnectionPool } from "./connections.js"; import { installHudKeybind } from "./debug.js"; import { CatalogStore } from "./events.js"; import { mountHud, type Hud } from "./hud.js"; +import { + activeTab, + emptyLayout, + findLeaf, + freshId, + leaves, + type Layout, + type Node, +} from "./layout.js"; import { openSpawnModal } from "./spawn.js"; import { initTheme } from "./theme.js"; import { sessionName } from "./types.js"; @@ -67,17 +76,64 @@ root.replaceChildren(renderTopbar(store), shellEl); // The pool owns attach connections independently of the route: navigating away // parks a session (keeps it streaming); navigating back re-mounts it instantly. +// It can mount several panes at once — the layout tree decides how many. For now +// the tree only ever holds a single leaf (splits/tabs arrive in epic #37); this +// routes the existing single-session view through that model. let hud: Hud | undefined; const pool = new ConnectionPool({ - onActiveChange: (id) => { + onFocusChange: (id) => { sidebar.setActive(id); hud?.refresh(); }, + onRequestClose: (id) => { + pool.close(id); + // Drop back to the welcome pane via the router. + if (location.hash !== "#/" && location.hash !== "") location.hash = "#/"; + }, }); // Debug HUD (#20): a fixed-corner overlay on the active session's inferred // fields, off by default (Ctrl+Shift+D, or `?hud` in dev). -hud = mountHud(root, store, () => pool.active()); +hud = mountHud(root, store, () => pool.focused()); + +// ---- layout state ---- +// Single source of truth for what's mounted. Today it's derived from the hash +// route (one leaf per `#/attach/:id`); future issues let the user build splits +// and tabs on top of the same model. +const layout: Layout = emptyLayout(); + +function infoFor(sessionId: string) { + const s = store.snapshot().sessions.get(sessionId); + return s ? { name: sessionName(s), command: s.command, daemon: s.daemon_id } : undefined; +} + +/** Show a single session in the active tab. */ +function openInLayout(sessionId: string): void { + const tab = activeTab(layout); + const leaf: Node = { kind: "leaf", id: freshId("l"), sessionId }; + tab.root = leaf; + tab.focusedLeafId = leaf.id; +} + +/** Empty the active tab (welcome / not-found). */ +function clearLayout(): void { + const tab = activeTab(layout); + tab.root = null; + tab.focusedLeafId = null; +} + +/** Reconcile the pool's visible panes + focus with the active tab's tree. */ +function renderLayout(): void { + const tab = activeTab(layout); + if (!tab.root) { + pool.parkActive(); + return; + } + const ls = leaves(tab.root); + pool.setVisible(ls.map((l) => ({ id: l.sessionId, pane: content, info: infoFor(l.sessionId) }))); + const focusLeaf = tab.focusedLeafId ? findLeaf(tab.root, tab.focusedLeafId) : ls[0]; + pool.setFocus(focusLeaf?.sessionId ?? null); +} function renderWelcome(): HTMLElement { const el = document.createElement("div"); @@ -128,23 +184,21 @@ function parseRoute(): Route { function dispatch(): void { const route = parseRoute(); switch (route.kind) { - case "attach": { + case "attach": shellEl.dataset.route = "attach"; - const s = store.snapshot().sessions.get(route.sessionId); - const info = s - ? { name: sessionName(s), command: s.command, daemon: s.daemon_id } - : undefined; - pool.activate(route.sessionId, content, info); + openInLayout(route.sessionId); + renderLayout(); return; - } case "not-found": shellEl.dataset.route = "notfound"; - pool.parkActive(); + clearLayout(); + renderLayout(); content.replaceChildren(renderNotFound(route.raw)); return; case "catalog": shellEl.dataset.route = "catalog"; - pool.parkActive(); + clearLayout(); + renderLayout(); content.replaceChildren(renderWelcome()); return; }