diff --git a/web/src/stores/catalogStore.test.ts b/web/src/stores/catalogStore.test.ts new file mode 100644 index 0000000..10d4a19 --- /dev/null +++ b/web/src/stores/catalogStore.test.ts @@ -0,0 +1,206 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createCatalogStore, + INITIAL_BACKOFF_MS, + MAX_BACKOFF_MS, + type CatalogStore, + type Scheduler, +} from "./catalogStore.js"; +import type { CatalogEvent, Session } from "../types.js"; + +function session(id: string): Session { + return { + id, + cwd: "/home/n", + command: "bash", + env: {}, + metadata: {}, + status: "Running", + created_at: "2026-08-22T00:00:00Z", + } as Session; +} + +/** Just enough of a WebSocket for the store to drive, plus a way to push frames. */ +class FakeSocket { + onmessage: ((ev: { data: string }) => void) | null = null; + onopen: (() => void) | null = null; + onclose: (() => void) | null = null; + onerror: (() => void) | null = null; + closed = false; + + close(): void { + this.closed = true; + } + + open(): void { + this.onopen?.(); + } + + emit(event: CatalogEvent): void { + this.onmessage?.({ data: JSON.stringify(event) }); + } + + drop(): void { + this.onclose?.(); + } +} + +/** Scheduler that records delays instead of waiting them out. */ +function fakeScheduler(): Scheduler & { delays: number[]; runNext(): void } { + const queued: Array<() => void> = []; + return { + delays: [] as number[], + setTimer(fn, ms) { + this.delays.push(ms); + queued.push(fn); + return queued.length; + }, + clearTimer() {}, + runNext() { + queued.shift()?.(); + }, + }; +} + +function storeWith(sockets: FakeSocket[], refetch?: () => Promise) { + let i = 0; + const scheduler = fakeScheduler(); + const store = createCatalogStore({ + socket: () => sockets[i++] as unknown as WebSocket, + scheduler, + refetch, + }); + return { store, scheduler }; +} + +describe("catalogStore reducer", () => { + it("replaces state on Snapshot and applies deltas", () => { + const ws = new FakeSocket(); + const { store } = storeWith([ws]); + store.getState().start(); + + ws.emit({ type: "Snapshot", sessions: [session("a")] } as CatalogEvent); + expect([...store.getState().sessions.keys()]).toEqual(["a"]); + + ws.emit({ type: "SessionAdded", session: session("b") } as CatalogEvent); + expect([...store.getState().sessions.keys()].sort()).toEqual(["a", "b"]); + + ws.emit({ type: "SessionRemoved", id: "a" } as CatalogEvent); + expect([...store.getState().sessions.keys()]).toEqual(["b"]); + }); + + it("ignores a frame that is not JSON", () => { + const ws = new FakeSocket(); + const { store } = storeWith([ws]); + store.getState().start(); + ws.emit({ type: "Snapshot", sessions: [session("a")] } as CatalogEvent); + + ws.onmessage?.({ data: "not json" }); + + expect([...store.getState().sessions.keys()]).toEqual(["a"]); + }); + + it("refetches over REST when the server reports dropped frames", async () => { + const ws = new FakeSocket(); + const refetch = vi.fn(async () => [session("fresh")]); + const { store } = storeWith([ws], refetch); + store.getState().start(); + ws.emit({ type: "Snapshot", sessions: [session("stale")] } as CatalogEvent); + + ws.emit({ type: "Lagged", skipped: 4 } as CatalogEvent); + await vi.waitFor(() => expect(refetch).toHaveBeenCalledOnce()); + + expect([...store.getState().sessions.keys()]).toEqual(["fresh"]); + }); + + it("hands each subscriber a fresh sessions map it can diff against the previous one", () => { + const ws = new FakeSocket(); + const { store } = storeWith([ws]); + const seen: CatalogStore[] = []; + store.subscribe((s) => seen.push(s)); + store.getState().start(); + + ws.emit({ type: "Snapshot", sessions: [session("a")] } as CatalogEvent); + ws.emit({ type: "SessionAdded", session: session("b") } as CatalogEvent); + + const [afterSnapshot, afterAdd] = seen; + expect(afterSnapshot.sessions).not.toBe(afterAdd.sessions); + expect(afterSnapshot.sessions.size).toBe(1); + expect(afterAdd.sessions.size).toBe(2); + }); +}); + +describe("catalogStore reconnect", () => { + it("replaces a suspended socket immediately", () => { + const first = new FakeSocket(); + const second = new FakeSocket(); + const { store } = storeWith([first, second]); + store.getState().start(); + + store.getState().reconnect(); + + expect(first.closed).toBe(true); + second.open(); + // A late close from the old socket is deliberately ignored. + first.drop(); + expect(store.getState().backoff()).toBe(INITIAL_BACKOFF_MS); + }); + + it("doubles the delay per attempt and caps it", () => { + const sockets = Array.from({ length: 8 }, () => new FakeSocket()); + const { store, scheduler } = storeWith(sockets); + store.getState().start(); + + for (let i = 0; i < 7; i++) { + sockets[i].drop(); + scheduler.runNext(); + } + + expect(scheduler.delays[0]).toBe(INITIAL_BACKOFF_MS); + expect(scheduler.delays[1]).toBe(INITIAL_BACKOFF_MS * 2); + expect(scheduler.delays.at(-1)).toBe(MAX_BACKOFF_MS); + }); + + it("resets the delay once a connection opens", () => { + const sockets = [new FakeSocket(), new FakeSocket(), new FakeSocket()]; + const { store, scheduler } = storeWith(sockets); + store.getState().start(); + + sockets[0].drop(); + scheduler.runNext(); + expect(store.getState().backoff()).toBe(INITIAL_BACKOFF_MS * 2); + + sockets[1].open(); + expect(store.getState().backoff()).toBe(INITIAL_BACKOFF_MS); + }); + + it("stop() tears the socket down without scheduling a reconnect", () => { + const ws = new FakeSocket(); + const { store, scheduler } = storeWith([ws]); + store.getState().start(); + + store.getState().stop(); + ws.drop(); + + expect(ws.closed).toBe(true); + expect(scheduler.delays).toEqual([]); + }); +}); + +describe("catalogStore connected state", () => { + it("reports the socket opening and dropping", () => { + const sock = new FakeSocket(); + const store = createCatalogStore({ + socket: () => sock as unknown as WebSocket, + scheduler: fakeScheduler(), + }); + const seen: boolean[] = []; + store.subscribe((s) => seen.push(s.connected)); + store.getState().start(); + sock.open(); + sock.drop(); + + expect(seen).toEqual([true, false]); + }); +}); diff --git a/web/src/stores/catalogStore.ts b/web/src/stores/catalogStore.ts new file mode 100644 index 0000000..d4380d8 --- /dev/null +++ b/web/src/stores/catalogStore.ts @@ -0,0 +1,188 @@ +import { create } from "zustand"; + +import { eventsWsUrl, listSessions } from "../api.js"; +import type { CatalogEvent, Session, Uuid } from "../types.js"; + +export interface CatalogState { + sessions: Map; + /** The events socket's up/down state. Drives the daemon link (daemonLink.ts) + * — the socket dying is the first sign the daemon went down or was + * upgraded under the page. */ + connected: boolean; +} + +/** Opens the events socket. Injectable so the reducer and the backoff schedule + * can be driven without a server. */ +export type SocketFactory = () => WebSocket; + +/** Schedules a reconnect attempt; returns a handle `clearTimer` understands. */ +export interface Scheduler { + setTimer(fn: () => void, ms: number): number; + clearTimer(handle: number): void; +} + +const browserScheduler: Scheduler = { + setTimer: (fn, ms) => window.setTimeout(fn, ms), + clearTimer: (h) => window.clearTimeout(h), +}; + +/** Initial reconnect delay, doubling to `MAX_BACKOFF_MS`. */ +export const INITIAL_BACKOFF_MS = 500; +export const MAX_BACKOFF_MS = 10_000; + +export interface CatalogStoreOptions { + socket?: SocketFactory; + scheduler?: Scheduler; + /** Full-state refetch used when the server reports it dropped frames. */ + refetch?: () => Promise; +} + +export interface CatalogActions { + start(): void; + /** Replace a socket that may have gone stale while the browser was suspended. */ + reconnect(): void; + stop(): void; + /** Current reconnect delay, for tests asserting the backoff schedule. */ + backoff(): number; +} + +export type CatalogStore = CatalogState & CatalogActions; + +/** Builds an isolated catalog store — a socket/scheduler/refetch can be + * injected (tests), or defaulted to the real browser/daemon ones. The + * returned value is both a React hook (`useCatalog(selector)`) and a plain + * object (`useCatalog.getState()`, `useCatalog.subscribe(fn)`), so the + * reconnect/backoff machinery works the same whether or not React is + * driving it. */ +export function createCatalogStore(opts: CatalogStoreOptions = {}) { + const socketFactory = opts.socket ?? (() => new WebSocket(eventsWsUrl())); + const scheduler = opts.scheduler ?? browserScheduler; + const refetch = opts.refetch ?? listSessions; + + let ws: WebSocket | null = null; + let reconnectTimer: number | null = null; + let backoffMs = INITIAL_BACKOFF_MS; + + return create((set, get) => { + function apply(event: CatalogEvent): void { + switch (event.type) { + case "Snapshot": + set({ sessions: new Map(event.sessions.map((s) => [s.id, s])) }); + return; + case "SessionAdded": + case "SessionUpdated": { + const next = new Map(get().sessions); + next.set(event.session.id, event.session); + set({ sessions: next }); + return; + } + case "SessionRemoved": { + const next = new Map(get().sessions); + next.delete(event.id); + set({ sessions: next }); + return; + } + case "Lagged": + // Re-derive from REST to avoid showing stale state. + void resync(); + return; + } + } + + async function resync(): Promise { + try { + const sessions = await refetch(); + set({ sessions: new Map(sessions.map((s) => [s.id, s])) }); + } catch { + // surface in UI on next reconnect cycle; nothing else useful to do + } + } + + function connect(): void { + const socket = socketFactory(); + ws = socket; + + socket.onmessage = (ev) => { + let event: CatalogEvent; + try { + event = JSON.parse(ev.data) as CatalogEvent; + } catch { + return; + } + apply(event); + }; + + socket.onopen = () => { + backoffMs = INITIAL_BACKOFF_MS; + set({ connected: true }); + }; + + socket.onclose = () => { + ws = null; + set({ connected: false }); + scheduleReconnect(); + }; + + socket.onerror = () => { + try { + socket.close(); + } catch { + // ignore + } + }; + } + + function scheduleReconnect(): void { + if (reconnectTimer !== null) return; + const delay = Math.min(backoffMs, MAX_BACKOFF_MS); + reconnectTimer = scheduler.setTimer(() => { + reconnectTimer = null; + backoffMs = Math.min(backoffMs * 2, MAX_BACKOFF_MS); + connect(); + }, delay); + } + + return { + sessions: new Map(), + connected: false, + + start() { + connect(); + }, + + reconnect() { + if (reconnectTimer !== null) { + scheduler.clearTimer(reconnectTimer); + reconnectTimer = null; + } + if (ws) { + // A close event from the superseded socket must not schedule a + // second connection alongside the new one. + ws.onclose = null; + ws.onerror = null; + ws.close(); + ws = null; + } + connect(); + }, + + stop() { + if (reconnectTimer !== null) { + scheduler.clearTimer(reconnectTimer); + reconnectTimer = null; + } + if (ws) { + ws.onclose = null; + ws.close(); + ws = null; + } + }, + + backoff() { + return backoffMs; + }, + }; + }); +} + +export type CatalogStoreApi = ReturnType; diff --git a/web/src/stores/connectionStore.test.ts b/web/src/stores/connectionStore.test.ts new file mode 100644 index 0000000..80d4917 --- /dev/null +++ b/web/src/stores/connectionStore.test.ts @@ -0,0 +1,414 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { createConnectionStore } from "./connectionStore.js"; +import { createCatalogStore } from "./catalogStore.js"; +import type { Session } from "../types.js"; + +// The pane's own bytes-out path, stubbed: the escape hatch only needs to know +// the pool reaches the focused connection with them. +const sent: { id: string; data: string }[] = []; +const disposed: string[] = []; +const mounts: { id: string; focus: boolean | undefined }[] = []; +function fakeConn(kind: string, id: string) { + const el = document.createElement("div"); + el.tabIndex = -1; // focusable via .focus(), like a real input/terminal + el.dataset.kind = kind; + el.dataset.session = id; + return { + sessionId: id, + kind, + el, + onMount(opts?: { focus?: boolean }) { + mounts.push({ id, focus: opts?.focus }); + }, + onUnmount() {}, + focusTerminal() {}, + sendInput(data: string) { + sent.push({ id, data }); + }, + updateInfo() {}, + dispose() { + disposed.push(`${kind}:${id}`); + }, + }; +} +vi.mock("../attach.js", () => ({ + createAttachConnection: (id: string) => fakeConn("attach", id), +})); +vi.mock("../structured.js", () => ({ + createStructuredConnection: (id: string) => fakeConn("structured", id), +})); + +afterEach(() => { + vi.unstubAllGlobals(); + sent.length = 0; + disposed.length = 0; + mounts.length = 0; +}); + +/** Minimal fixture for the sessions map a catalog store broadcasts. */ +function session(id: string, view?: "Terminal" | "Structured"): Session { + return { + id, + cwd: "/repo", + command: "claude", + env: {}, + metadata: {}, + status: "Running", + created_at: "2026-01-01T00:00:00Z", + view, + }; +} + +/** A catalog store an id can be pushed into on demand, mirroring + * catalogStore.test.ts's own injectable-socket pattern. */ +class FakeCatalogSocket { + onmessage: ((ev: { data: string }) => void) | null = null; + onopen: (() => void) | null = null; + onclose: (() => void) | null = null; + onerror: (() => void) | null = null; + close(): void {} + push(sessions: Session[]): void { + this.onmessage?.({ data: JSON.stringify({ type: "Snapshot", sessions }) }); + } +} +function fakeCatalog() { + const socket = new FakeCatalogSocket(); + const store = createCatalogStore({ socket: () => socket as unknown as WebSocket }); + store.getState().start(); + return { store, socket }; +} + +const A = "aaaaaaaa-0000-0000-0000-0000000000ff"; +const B = "bbbbbbbb-0000-0000-0000-0000000000ff"; + +function mockFetch() { + const fetchMock = vi.fn(() => Promise.resolve(new Response(null, { status: 204 }))); + vi.stubGlobal("fetch", fetchMock); + return fetchMock; +} + +describe("connectionStore setFocus", () => { + it("reports the new session focused, none unfocused, the first time", () => { + const fetchMock = mockFetch(); + const pool = createConnectionStore(); + + pool.getState().setFocus(A); + + expect(fetchMock).toHaveBeenCalledOnce(); + const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe(`/api/sessions/${A}/focus`); + expect(init.method).toBe("POST"); + expect(JSON.parse(init.body as string)).toEqual({ focused: true }); + expect(pool.getState().focusedId).toBe(A); + }); + + it("unfocuses the previous session and focuses the new one on a switch", () => { + const fetchMock = mockFetch(); + const pool = createConnectionStore(); + pool.getState().setFocus(A); + fetchMock.mockClear(); + + pool.getState().setFocus(B); + + expect(fetchMock).toHaveBeenCalledTimes(2); + const bodies = fetchMock.mock.calls.map(([url, init]: unknown[]) => [ + url, + JSON.parse((init as RequestInit).body as string), + ]); + expect(bodies).toContainEqual([`/api/sessions/${A}/focus`, { focused: false }]); + expect(bodies).toContainEqual([`/api/sessions/${B}/focus`, { focused: true }]); + }); + + it("reports unfocused when focus clears to null", () => { + const fetchMock = mockFetch(); + const pool = createConnectionStore(); + pool.getState().setFocus(A); + fetchMock.mockClear(); + + pool.getState().setFocus(null); + + expect(fetchMock).toHaveBeenCalledOnce(); + const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe(`/api/sessions/${A}/focus`); + expect(JSON.parse(init.body as string)).toEqual({ focused: false }); + }); + + it("is a no-op when the focused session doesn't change", () => { + const fetchMock = mockFetch(); + const pool = createConnectionStore(); + pool.getState().setFocus(A); + fetchMock.mockClear(); + + pool.getState().setFocus(A); + + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("does not let a fetch rejection break the pool", async () => { + vi.stubGlobal( + "fetch", + vi.fn(() => Promise.reject(new Error("offline"))), + ); + const pool = createConnectionStore(); + + expect(() => pool.getState().setFocus(A)).not.toThrow(); + // Let the rejected promise's `.catch` settle before the test ends. + await Promise.resolve(); + await Promise.resolve(); + }); +}); + +describe("connectionStore sendToFocused", () => { + it("types the bytes into the focused session's PTY", () => { + mockFetch(); + sent.length = 0; + const pool = createConnectionStore(); + const pane = document.createElement("div"); + pool.getState().mount(A, pane); + pool.getState().setFocus(A); + + expect(pool.getState().sendToFocused("\x0b")).toBe(true); + expect(sent).toEqual([{ id: A, data: "\x0b" }]); + }); + + it("is a no-op with nothing focused", () => { + mockFetch(); + sent.length = 0; + const pool = createConnectionStore(); + + expect(pool.getState().sendToFocused("\x0b")).toBe(false); + expect(sent).toEqual([]); + }); +}); + +describe("connectionStore mount/unmount", () => { + it("tracks mounted and LRU order reactively", () => { + mockFetch(); + const pool = createConnectionStore(); + const paneA = document.createElement("div"); + const paneB = document.createElement("div"); + + pool.getState().mount(A, paneA); + pool.getState().mount(B, paneB); + expect(pool.getState().cacheOrder).toEqual([A, B]); + expect([...pool.getState().mounted]).toEqual([A, B]); + + pool.getState().unmount(A); + expect([...pool.getState().mounted]).toEqual([B]); + // Parked, not evicted — still in LRU order. + expect(pool.getState().cacheOrder).toEqual([A, B]); + + pool.getState().close(A); + expect(pool.getState().cacheOrder).toEqual([B]); + expect(disposed).toEqual(["attach:" + A]); + }); + + it("evicts the least-recently-viewed parked connection beyond MAX_PARKED", () => { + mockFetch(); + const pool = createConnectionStore(); + const ids = Array.from({ length: 8 }, (_, i) => `id-${i}`); + for (const id of ids) { + pool.getState().mount(id, document.createElement("div")); + pool.getState().unmount(id); // park immediately + } + + // Each mount only has itself visible (the rest already parked), so the + // cap-crossing eviction fires once, on the mount that pushes the parked + // count from 6 to 7: the single oldest (id-0) is dropped. + expect(disposed).toEqual(["attach:id-0"]); + expect(pool.getState().cacheOrder).toEqual(ids.slice(1)); + }); +}); + +// A deep link or restored layout can `mount()` a session before the catalog +// snapshot names its view — the daemon defaults an absent `view` to +// `"Terminal"`, but so does an *unknown* session, and only one of those is +// actually resolved (#140 review). +describe("connectionStore: view resolution races", () => { + it("replaces a wrongly-typed connection once the catalog resolves it, without waiting for another mount()", () => { + mockFetch(); + const { store, socket } = fakeCatalog(); + const pool = createConnectionStore({ store }); + const pane = document.createElement("div"); + + pool.getState().mount(A, pane); // no info: deep-link-before-snapshot race + expect(disposed).toEqual([]); + + socket.push([session(A, "Structured")]); + + expect(disposed).toEqual(["attach:" + A]); + // The fresh connection landed in the same pane nothing re-mounted it into. + expect(pane.children).toHaveLength(1); + }); + + it("also repairs a wrongly-typed connection that is parked, not mounted, without evicting its other parked siblings", () => { + mockFetch(); + const { store, socket } = fakeCatalog(); + const pool = createConnectionStore({ store }); + const hidden = document.body.lastElementChild as HTMLElement; // this pool's own cache + pool.getState().mount(A, document.createElement("div")); + pool.getState().mount(B, document.createElement("div")); + pool.getState().unmount(A); + pool.getState().unmount(B); + disposed.length = 0; + + socket.push([session(A, "Structured")]); + + expect(disposed).toEqual(["attach:" + A]); + // B's own element is still parked — A's repair didn't wipe its siblings + // out of the shared hidden cache. + expect(hidden.querySelector(`[data-session="${B}"]`)).not.toBeNull(); + expect((hidden.querySelector(`[data-session="${A}"]`) as HTMLElement | null)?.dataset.kind).toBe("structured"); + }); + + it("does not replace a connection whose resolved view already matches", () => { + mockFetch(); + const { store, socket } = fakeCatalog(); + const pool = createConnectionStore({ store }); + const pane = document.createElement("div"); + pool.getState().mount(A, pane, { name: "a", command: "claude", view: "Structured" }); + disposed.length = 0; + + socket.push([session(A, "Structured")]); + + expect(disposed).toEqual([]); + }); + + it("does not downgrade an already-resolved connection when a later mount() call has no info", () => { + mockFetch(); + const pool = createConnectionStore(); + const pane = document.createElement("div"); + pool.getState().mount(A, pane, { name: "a", command: "claude", view: "Structured" }); + disposed.length = 0; + + pool.getState().mount(A, pane); // e.g. a re-render before the catalog answers again + + expect(disposed).toEqual([]); + }); + + it("does not treat a session missing from the catalog as Terminal and churn a live connection", () => { + mockFetch(); + const { store, socket } = fakeCatalog(); + const pool = createConnectionStore({ store }); + const pane = document.createElement("div"); + pool.getState().mount(A, pane, { name: "a", command: "claude", view: "Structured" }); + disposed.length = 0; + + // `A` is absent from this snapshot — the embedder's own subscription + // handles closing the pane; the pool must not race it by "fixing" the + // view first. + socket.push([session(B, "Terminal")]); + + expect(disposed).toEqual([]); + }); + + it("re-focuses the fresh connection when the keyboard was actually inside the replaced pane", () => { + mockFetch(); + const { store, socket } = fakeCatalog(); + const pool = createConnectionStore({ store }); + const pane = document.createElement("div"); + document.body.appendChild(pane); + pool.getState().mount(A, pane); + pool.getState().setFocus(A); + (pane.firstElementChild as HTMLElement).focus(); + expect(document.activeElement).toBe(pane.firstElementChild); + mounts.length = 0; + + socket.push([session(A, "Structured")]); + + expect(disposed).toEqual(["attach:" + A]); + expect(mounts).toEqual([{ id: A, focus: true }]); + pane.remove(); + }); + + it("does not steal focus from a same-tab sidebar preview even though focusedId still names the previous pane", () => { + mockFetch(); + const { store, socket } = fakeCatalog(); + const pool = createConnectionStore({ store }); + const pane = document.createElement("div"); + document.body.appendChild(pane); + pool.getState().mount(A, pane); + pool.getState().setFocus(A); + (pane.firstElementChild as HTMLElement).focus(); + + const sidebarInput = document.createElement("input"); + document.body.appendChild(sidebarInput); + sidebarInput.focus(); + expect(document.activeElement).toBe(sidebarInput); + mounts.length = 0; + + socket.push([session(A, "Structured")]); + + expect(disposed).toEqual(["attach:" + A]); + expect(mounts).toEqual([{ id: A, focus: false }]); + pane.remove(); + sidebarInput.remove(); + }); + + it("does not focus a parked (unmounted) connection it repairs", () => { + mockFetch(); + const { store, socket } = fakeCatalog(); + const pool = createConnectionStore({ store }); + const pane = document.createElement("div"); + pool.getState().mount(A, pane); + pool.getState().setFocus(A); + pool.getState().unmount(A); // parked — no longer visible, `focusedId` still names it + mounts.length = 0; + + socket.push([session(A, "Structured")]); + + expect(disposed).toEqual(["attach:" + A]); + expect(mounts).toEqual([]); // parked repair calls onUnmount, never onMount + }); +}); + +describe("connectionStore setVisible/activate/parkActive", () => { + it("parks sessions not in the next visible set and mounts the rest", () => { + mockFetch(); + const pool = createConnectionStore(); + const paneA = document.createElement("div"); + const paneB = document.createElement("div"); + pool.getState().setVisible([ + { id: A, pane: paneA }, + { id: B, pane: paneB }, + ]); + expect([...pool.getState().mounted].sort()).toEqual([A, B]); + + pool.getState().setVisible([{ id: B, pane: paneB }]); + + expect([...pool.getState().mounted]).toEqual([B]); + }); + + it("activate mounts+focuses alone, parkActive parks all and clears focus", () => { + mockFetch(); + const pool = createConnectionStore(); + const pane = document.createElement("div"); + + pool.getState().activate(A, pane); + expect(pool.getState().focusedId).toBe(A); + expect(pool.getState().isMounted(A)).toBe(true); + + pool.getState().parkActive(); + expect(pool.getState().focusedId).toBeNull(); + expect(pool.getState().isMounted(A)).toBe(false); + }); +}); + +describe("connectionStore dispose", () => { + it("disposes every cached connection and resets state", () => { + mockFetch(); + const pool = createConnectionStore(); + pool.getState().mount(A, document.createElement("div")); + pool.getState().mount(B, document.createElement("div")); + disposed.length = 0; + + pool.getState().dispose(); + + expect(disposed.sort()).toEqual(["attach:" + A, "attach:" + B]); + expect(pool.getState().mounted.size).toBe(0); + expect(pool.getState().cacheOrder).toEqual([]); + expect(pool.getState().focusedId).toBeNull(); + }); +}); diff --git a/web/src/stores/connectionStore.ts b/web/src/stores/connectionStore.ts new file mode 100644 index 0000000..0e404b3 --- /dev/null +++ b/web/src/stores/connectionStore.ts @@ -0,0 +1,360 @@ +import { create } from "zustand"; + +import { createAttachConnection } from "../attach.js"; +import type { AttachInfo } from "../paneTitle.js"; +import type { PaneConnection } from "../pane.js"; +import { createStructuredConnection } from "../structured.js"; +import { setSessionFocus } from "../api.js"; +import { sessionName, type Session, type SessionView, type Uuid } from "../types.js"; +import type { CatalogStoreApi } from "./catalogStore.js"; + +/** + * 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_PARKED = 6; + +/** A session's view defaults to `"Terminal"` wherever it isn't carried — + * matching the wire default (`SessionView`'s `#[default]`, types.ts). Only + * meaningful once the session itself is known; an altogether-unknown + * session (no `AttachInfo`/`Session` at all) is a distinct, un-resolved + * state callers must check for separately, not "Terminal". */ +function resolveView(view: SessionView | undefined): SessionView { + return view ?? "Terminal"; +} + +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; + /** Fired when a connection's socket closes on its own (session ended/dropped), + * not via an intentional close/eviction. The embedder closes the pane. */ + onClosed?: (id: Uuid) => void; + /** Forwarded to each connection: should a dropped socket be retried? */ + shouldReconnect?: (id: Uuid, code: number) => boolean; + /** Threaded through to a structured connection so its rail can read live + * worktree/git-status data (#140). Terminal connections don't need it. */ + store?: CatalogStoreApi; +} + +export interface ConnectionState { + /** Sessions currently mounted into a visible pane. */ + mounted: Set; + /** Every live (mounted or parked) connection, oldest first — LRU order. */ + cacheOrder: Uuid[]; + /** The focused session, or null when nothing is focused (welcome pane). */ + focusedId: Uuid | null; +} + +export interface ConnectionActions { + isMounted(id: Uuid): boolean; + /** + * Ensure `id` is live and shown inside `pane`, reusing its connection if one + * exists (refreshing LRU recency). Does not touch other mounted panes. + */ + mount(id: Uuid, pane: HTMLElement, info?: AttachInfo, opts?: { focus?: boolean }): void; + /** Park `id` back into the hidden cache (still connected) and stop showing it. */ + unmount(id: Uuid): void; + /** + * Reconcile the visible set to exactly `entries` (in render order): park any + * mounted session not listed, mount/refresh each listed one in its pane. + * `focus: false` shows the panes without taking the keyboard (preview). + */ + setVisible(entries: { id: Uuid; pane: HTMLElement; info?: AttachInfo }[], opts?: { focus?: boolean }): void; + /** Also tells the daemon which pane is focused (docs/SIDEBAR.md's + * `AwaitingInput` auto-clear) — the sidebar highlight never calls this, + * only a pane actually becoming the visible view. Best-effort: a failed + * report only delays the glow clearing. */ + setFocus(id: Uuid | null): void; + /** Compat shim: show `id` alone in `pane` and focus it; park everything else. */ + activate(id: Uuid, pane: HTMLElement, info?: AttachInfo): void; + /** Compat shim: park all visible panes and clear focus (e.g. welcome pane). */ + parkActive(): void; + /** Put the keyboard back into the focused session's terminal. No-op when + * nothing is focused (welcome pane) or its connection is gone. */ + focusTerminal(): void; + /** Type raw bytes into the focused session's PTY. Returns false when there is + * nothing focused, or its connection is gone — the leader's literal Ctrl-K + * is a no-op over the welcome pane rather than an error + * (docs/COMMAND-BAR.md). */ + sendToFocused(data: string): boolean; + /** Fully disconnect + forget a session. */ + close(id: Uuid): void; + dispose(): void; +} + +export type ConnectionStore = ConnectionState & ConnectionActions; + +/** + * Builds an isolated connection store — owns the set of live attach + * connections, decoupled from the router/UI. The returned value is both a + * React hook and a plain object (`getState`/`subscribe`), same shape as + * {@link createCatalogStore}. + * + * Unlike a single-active pool, several connections can be **mounted** + * (visible) at once — one per leaf of the active tab's layout tree. The + * caller reconciles the visible set with {@link ConnectionActions.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 ConnectionActions.close}, or {@link ConnectionActions.dispose}. + */ +export function createConnectionStore(opts: PoolOptions = {}) { + /** All live connections. Insertion order doubles as LRU: oldest first. */ + const cache = new Map(); + /** The view each cached connection was actually created for — a deep link + * or a restored layout can `mount()` a session before the catalog + * snapshot names its view, defaulting it to `"Terminal"`; this is what + * lets a later reconciliation notice the resolved view disagrees (#140 + * review). */ + const connViews = new Map(); + // Off-screen home for parked, still-connected terminals. + const hidden = document.createElement("div"); + hidden.className = "conn-cache"; + hidden.setAttribute("aria-hidden", "true"); + document.body.appendChild(hidden); + + let unsubscribeStore: (() => void) | undefined; + + const store = create((set, get) => { + function createConn(id: Uuid, info?: AttachInfo): PaneConnection { + const view = resolveView(info?.view); + connViews.set(id, view); + const connOpts = { + onRequestClose: (sid: Uuid) => opts.onRequestClose?.(sid), + onClosed: (sid: Uuid) => opts.onClosed?.(sid), + shouldReconnect: (sid: Uuid, code: number) => opts.shouldReconnect?.(sid, code) ?? false, + }; + // structured.ts's own `store` param still expects the pre-Zustand + // `CatalogStore` class (events.ts) and doesn't use it yet (#140) — left + // unpassed here until that rail wiring is ported too. + return view === "Structured" + ? createStructuredConnection(id, connOpts, info) + : createAttachConnection(id, connOpts, info); + } + + /** Dispose whatever is cached for `id` and cache a freshly created + * connection in its place. Does not touch the DOM, `mounted`, or LRU + * order — callers place the new element themselves. */ + function replace(id: Uuid, info?: AttachInfo): PaneConnection { + cache.get(id)?.dispose(); + const fresh = createConn(id, info); + cache.set(id, fresh); + return fresh; + } + + function insertOrder(id: Uuid): void { + set((s) => ({ cacheOrder: [...s.cacheOrder, id] })); + } + + function touchOrder(id: Uuid): void { + set((s) => ({ cacheOrder: [...s.cacheOrder.filter((x) => x !== id), id] })); + } + + function removeOrder(id: Uuid): void { + set((s) => ({ cacheOrder: s.cacheOrder.filter((x) => x !== id) })); + } + + function setMounted(id: Uuid, isMounted: boolean): void { + set((s) => { + if (s.mounted.has(id) === isMounted) return {}; + const next = new Set(s.mounted); + if (isMounted) next.add(id); + else next.delete(id); + return { mounted: next }; + }); + } + + function setFocus(id: Uuid | null): void { + const previous = get().focusedId; + if (id === previous) return; + set({ focusedId: id }); + if (previous !== null) void setSessionFocus(previous, false).catch(() => {}); + if (id !== null) void setSessionFocus(id, true).catch(() => {}); + opts.onFocusChange?.(id); + } + + function close(id: Uuid): void { + const conn = cache.get(id); + if (!conn) return; + conn.dispose(); + cache.delete(id); + connViews.delete(id); + removeOrder(id); + setMounted(id, false); + if (get().focusedId === id) setFocus(null); + } + + /** Drop least-recently-viewed *parked* connections beyond the buffer cap. */ + function evict(): void { + while (cache.size - get().mounted.size > MAX_PARKED) { + const mounted = get().mounted; + let victim: Uuid | null = null; + for (const id of cache.keys()) { + if (!mounted.has(id)) { + victim = id; + break; + } + } + if (victim === null) break; + close(victim); + } + } + + function mount(id: Uuid, pane: HTMLElement, info?: AttachInfo, mountOpts?: { focus?: boolean }): void { + let conn = cache.get(id); + if (conn) { + // `info === undefined` means "session not known yet", not "Terminal" — + // never downgrade a resolved connection just because a later caller + // couldn't resolve the session. Only a *resolved* view that disagrees + // with what this connection was built for forces a replace. + if (info !== undefined && resolveView(info.view) !== connViews.get(id)) { + conn = replace(id, info); + } else { + touchOrder(id); + if (info) conn.updateInfo(info); + } + } else { + conn = createConn(id, info); + cache.set(id, conn); + insertOrder(id); + } + if (conn.el.parentElement !== pane) { + pane.replaceChildren(conn.el); + conn.onMount(mountOpts); + } else if (!get().mounted.has(id)) { + conn.onMount(mountOpts); + } + setMounted(id, true); + evict(); + } + + function unmount(id: Uuid): void { + if (!get().mounted.has(id)) return; + setMounted(id, false); + const conn = cache.get(id); + if (conn) { + hidden.appendChild(conn.el); // stays alive, just off-screen + conn.onUnmount(); + } + } + + function setVisible( + entries: { id: Uuid; pane: HTMLElement; info?: AttachInfo }[], + visOpts?: { focus?: boolean }, + ): void { + const next = new Set(entries.map((e) => e.id)); + for (const id of [...get().mounted]) { + if (!next.has(id)) unmount(id); + } + for (const e of entries) mount(e.id, e.pane, e.info, visOpts); + } + + /** Proactively fix any cached connection whose view no longer matches the + * catalog — the only path that repairs a pane nothing will `mount()` + * again on its own (parked, or mounted but not currently being + * re-rendered by anything else). A session absent from `sessions` (not + * yet known, or removed) is left alone — that's the embedder's own + * close/eviction concern, not a view mismatch. */ + function reconcileViews(sessions: Map): void { + for (const id of [...cache.keys()]) { + const session = sessions.get(id); + if (session === undefined || resolveView(session.view) === connViews.get(id)) continue; + const existing = cache.get(id)!; + const parent = existing.el.parentElement; + const wasMounted = get().mounted.has(id); + // Capture before anything below touches the DOM: dispose()/el.remove() + // detach `existing.el`, and once a focused descendant is detached the + // browser moves `document.activeElement` to `` — too late to + // tell whether the keyboard was actually in this pane. + const hadDomFocus = existing.el.contains(document.activeElement); + const info: AttachInfo = { name: sessionName(session), command: session.command, view: session.view }; + const fresh = replace(id, info); + existing.el.remove(); // don't rely on dispose() to clear the DOM + if (parent && parent !== hidden) { + parent.replaceChildren(fresh.el); + } else { + // Parked: `hidden` holds every parked connection's element as + // siblings — append, never replaceChildren, or they'd all vanish. + hidden.appendChild(fresh.el); + } + if (wasMounted) { + // `focusedId` names the session the pool was last told to focus — + // but a same-tab sidebar preview moves the keyboard into the + // sidebar without clearing it, so `focusedId` alone can point at a + // pane the keyboard already left. Only re-focus when the DOM + // agrees it never did. + fresh.onMount({ focus: get().focusedId === id && hadDomFocus }); + } else { + fresh.onUnmount(); + } + } + } + + // A session `mount()`ed before its catalog entry exists gets a + // `"Terminal"` connection by default; once the snapshot actually names + // the view, fix any connection that guessed wrong — nothing else + // re-`mount()`s an already-open pane just because the catalog updated. + unsubscribeStore = opts.store?.subscribe((state) => reconcileViews(state.sessions)); + + return { + mounted: new Set(), + cacheOrder: [], + focusedId: null, + + isMounted(id) { + return get().mounted.has(id); + }, + + mount, + unmount, + setVisible, + setFocus, + + activate(id, pane, info) { + setVisible([{ id, pane, info }]); + setFocus(id); + }, + + parkActive() { + for (const id of [...get().mounted]) unmount(id); + setFocus(null); + }, + + focusTerminal() { + const id = get().focusedId; + if (id === null) return; + cache.get(id)?.focusTerminal(); + }, + + sendToFocused(data) { + const id = get().focusedId; + if (id === null) return false; + const conn = cache.get(id); + if (!conn) return false; + conn.sendInput(data); + return true; + }, + + close, + + dispose() { + unsubscribeStore?.(); + for (const conn of cache.values()) conn.dispose(); + cache.clear(); + connViews.clear(); + set({ mounted: new Set(), cacheOrder: [], focusedId: null }); + hidden.remove(); + }, + }; + }); + + return store; +} + +export type ConnectionStoreApi = ReturnType;