test(maestro): give the SPA a test runner and a reachable pure core
ci / rust (pull_request) Successful in 2m28s
ci / web (pull_request) Successful in 23s
ci / web (push) Successful in 26s
ci / rust (push) Successful in 1m38s

The browser app had no tests and no way to run any: package.json shipped
dev/build/preview/typecheck, and CI installed Node and pnpm but never ran
anything with them. Its densest logic was module-private, so even with a
runner none of it was reachable.

Extracts four pure modules out of DOM-heavy ones — tree.ts (directory
grouping), keys.ts (terminal escape encoding), paths.ts (completion
arithmetic), html.ts (one escaper, replacing four copies). Extraction
rather than `export` because attach.ts imports xterm's CSS at module
level, which a node test cannot load.

CatalogStore takes an injectable socket factory, scheduler and refetch, so
the reducer and the backoff schedule run without a server. snapshot() now
returns a copy: it returned the live object while events mutated it in
place, so listeners could not diff and every event rebuilt the whole tree.

36 tests across 6 files, and a `web` CI job running typecheck, test and
build. vitest is pinned to 2.x — 4.x requires vite >= 6 and this is vite 5.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit was merged in pull request #44.
This commit is contained in:
Miguel Palhas
2026-08-22 14:08:14 +01:00
co-authored by Claude Opus 5
parent db44650a17
commit 031c80a40b
20 changed files with 1037 additions and 187 deletions
+6 -37
View File
@@ -3,6 +3,8 @@ import { Terminal } from "@xterm/xterm";
import "@xterm/xterm/css/xterm.css";
import { attachWsUrl } from "./routes.js";
import { escapeHtml } from "./html.js";
import { applyModsToChar, cursorSeq } from "./keys.js";
import type { ClientControl, Uuid } from "./types.js";
/**
@@ -44,14 +46,6 @@ export interface AttachInfo {
command: string;
}
function esc(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
export function createAttachConnection(
sessionId: Uuid,
opts: AttachOptions = {},
@@ -62,16 +56,16 @@ export function createAttachConnection(
// Useful identity over a bare UUID: name · command. The full id stays in the
// tooltip for when you really need it.
const titleHtml = info
? `<span class="at-name">${esc(info.name)}</span>` +
? `<span class="at-name">${escapeHtml(info.name)}</span>` +
(info.command && info.command !== info.name
? `<span class="at-cmd">${esc(info.command)}</span>`
? `<span class="at-cmd">${escapeHtml(info.command)}</span>`
: "")
: `session <span class="sid">${esc(sessionId.slice(0, 8))}</span>`;
: `session <span class="sid">${escapeHtml(sessionId.slice(0, 8))}</span>`;
const titleAttr = info ? `${info.name} · ${info.command} (${sessionId})` : sessionId;
el.innerHTML = `
<header class="attach-header">
<a class="btn btn-ghost back" href="#/" aria-label="Back to catalog" title="Back to catalog">←</a>
<span class="attach-title" title="${esc(titleAttr)}">${titleHtml}</span>
<span class="attach-title" title="${escapeHtml(titleAttr)}">${titleHtml}</span>
<span class="attach-state" data-state="connecting">connecting…</span>
<button class="btn btn-ghost btn-icon disconnect" type="button" aria-label="Disconnect" title="Disconnect this session">⏻</button>
</header>
@@ -422,31 +416,6 @@ const KEY_DEFS: KeyDef[] = [
* Fold a single character into its control code: letters and `@[\]^_` map to
* 0x00–0x1f, space → NUL, `?` → DEL. Anything else is returned unchanged.
*/
function toCtrl(ch: string): string {
if (ch.length !== 1) return ch;
const upper = ch.toUpperCase().codePointAt(0) ?? 0;
if (upper >= 0x40 && upper <= 0x5f) return String.fromCodePoint(upper & 0x1f);
if (ch === " ") return "\x00";
if (ch === "?") return "\x7f";
return ch;
}
/** Apply pending modifiers to a single typed character: Ctrl → control code,
* Alt → ESC prefix (xterm meta). Both compose (Ctrl+Alt = ESC + control). */
function applyModsToChar(ch: string, ctrl: boolean, alt: boolean): string {
let out = ctrl ? toCtrl(ch) : ch;
if (alt) out = "\x1b" + out;
return out;
}
/** Cursor/nav-key sequence, promoted to the modified CSI form when Ctrl/Alt are
* pending — `\x1b[1;<n><final>`, n = 1 + alt(2) + ctrl(4) (xterm convention). */
function cursorSeq(final: string, ctrl: boolean, alt: boolean): string {
if (!ctrl && !alt) return `\x1b[${final}`;
const n = 1 + (alt ? 2 : 0) + (ctrl ? 4 : 0);
return `\x1b[1;${n}${final}`;
}
interface KeyBar {
readonly el: HTMLElement;
/** Fold pending modifiers into typed input (soft keyboard), consuming them. */
+4 -88
View File
@@ -1,92 +1,16 @@
import { escapeHtml } from "./html.js";
import { getDaemonInfo, killSession } from "./api.js";
import { HUD_TOGGLE_EVENT, isHudEnabled, toggleHud } from "./debug.js";
import { CatalogStore } from "./events.js";
import type { Session } from "./types.js";
import { abbreviateCwd, abbreviateFolderName, sessionCwd, sessionName } from "./types.js";
import { abbreviateFolderName, sessionName } from "./types.js";
import type { TreeNode } from "./tree.js";
import { buildTree } from "./tree.js";
import { openSpawnModal } from "./spawn.js";
import { createThemeToggle } from "./theme.js";
interface TreeFolder {
kind: "folder";
name: string;
path: string;
children: TreeNode[];
}
interface TreeLeaf {
kind: "leaf";
session: Session;
}
type TreeNode = TreeFolder | TreeLeaf;
const collapsed = new Set<string>();
function compareNodes(a: TreeNode, b: TreeNode): number {
if (a.kind !== b.kind) return a.kind === "folder" ? -1 : 1;
const an = a.kind === "folder" ? a.name : sessionName(a.session);
const bn = b.kind === "folder" ? b.name : sessionName(b.session);
return an.localeCompare(bn);
}
function buildTree(sessions: Session[], home: string | undefined, filter: string): TreeNode {
const root: TreeFolder = { kind: "folder", name: "", path: "", children: [] };
const lc = filter.trim().toLowerCase();
for (const s of sessions) {
const cwd = sessionCwd(s);
const dir = cwd ? abbreviateCwd(cwd, home) : "";
if (lc) {
const haystack = `${sessionName(s)} ${dir}`.toLowerCase();
if (!haystack.includes(lc)) continue;
}
const parts = dir ? dir.split("/").filter(Boolean) : [];
let cursor = root;
for (const part of parts) {
const path = cursor.path ? `${cursor.path}/${part}` : part;
let next = cursor.children.find(
(n): n is TreeFolder => n.kind === "folder" && n.name === part,
);
if (!next) {
next = { kind: "folder", name: part, path, children: [] };
cursor.children.push(next);
}
cursor = next;
}
cursor.children.push({ kind: "leaf", session: s });
}
const sortRec = (n: TreeFolder) => {
n.children.sort(compareNodes);
for (const c of n.children) if (c.kind === "folder") sortRec(c);
};
sortRec(root);
// Collapse linear directory chains so `~/git.naps.pt/naps62/maestro` reads as
// one compact folder rather than four nested ones.
root.children = root.children.map((c) => (c.kind === "folder" ? mergeLinear(c) : c));
return root;
}
/** Fold a folder with a single folder-child into one node (`a` + `b` → `a/b`),
* repeating down the chain, then recurse into the surviving branches. The merged
* node keeps the deepest path so collapse/expand state stays stable as it grows. */
function mergeLinear(folder: TreeFolder): TreeFolder {
let cur = folder;
while (cur.children.length === 1 && cur.children[0].kind === "folder") {
const child = cur.children[0];
cur = {
kind: "folder",
name: `${cur.name}/${child.name}`,
path: child.path,
children: child.children,
};
}
cur.children = cur.children.map((c) =>
c.kind === "folder" ? mergeLinear(c) : c,
);
return cur;
}
function renderNode(node: TreeNode, depth: number): HTMLElement {
if (node.kind === "folder") {
const wrap = document.createElement("div");
@@ -163,14 +87,6 @@ function renderNode(node: TreeNode, depth: number): HTMLElement {
return row;
}
function escapeHtml(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function renderStatusbar(sessions: Session[]): HTMLElement {
const wrap = document.createElement("div");
wrap.className = "statusbar";
+1 -20
View File
@@ -12,6 +12,7 @@
//
// Failures (offline daemon, permission denied) degrade to no suggestions.
import { longestCommonPrefix, splitPath } from "./paths.js";
import { listDir } from "./api.js";
export interface DirAutocompleteHandle {
@@ -26,26 +27,6 @@ const FETCH_DEBOUNCE_MS = 90;
/** Split a path value into the directory to list and the trailing fragment
* being typed within it. The directory keeps its trailing `/` (or is empty,
* meaning "the daemon's home dir"). */
function splitPath(value: string): { dir: string; prefix: string } {
const slash = value.lastIndexOf("/");
if (slash === -1) return { dir: "", prefix: value };
return { dir: value.slice(0, slash + 1), prefix: value.slice(slash + 1) };
}
/** Longest common prefix of a list of strings (case-sensitive, preserving the
* actual on-disk casing). */
function longestCommonPrefix(items: string[]): string {
if (items.length === 0) return "";
let lcp = items[0];
for (const s of items.slice(1)) {
let i = 0;
while (i < lcp.length && i < s.length && lcp[i] === s[i]) i++;
lcp = lcp.slice(0, i);
if (lcp === "") break;
}
return lcp;
}
export function attachDirAutocomplete(input: HTMLInputElement): DirAutocompleteHandle {
const dropdown = document.createElement("ul");
dropdown.className = "dir-ac";
+162
View File
@@ -0,0 +1,162 @@
import { describe, expect, it, vi } from "vitest";
import {
CatalogStore,
INITIAL_BACKOFF_MS,
MAX_BACKOFF_MS,
type CatalogState,
type Scheduler,
} from "./events.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<Session[]>) {
let i = 0;
const scheduler = fakeScheduler();
const store = new CatalogStore({
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.start();
ws.emit({ type: "Snapshot", sessions: [session("a")] } as CatalogEvent);
expect([...store.snapshot().sessions.keys()]).toEqual(["a"]);
ws.emit({ type: "SessionAdded", session: session("b") } as CatalogEvent);
expect([...store.snapshot().sessions.keys()].sort()).toEqual(["a", "b"]);
ws.emit({ type: "SessionRemoved", id: "a" } as CatalogEvent);
expect([...store.snapshot().sessions.keys()]).toEqual(["b"]);
});
it("ignores a frame that is not JSON", () => {
const ws = new FakeSocket();
const { store } = storeWith([ws]);
store.start();
ws.emit({ type: "Snapshot", sessions: [session("a")] } as CatalogEvent);
ws.onmessage?.({ data: "not json" });
expect([...store.snapshot().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.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.snapshot().sessions.keys()]).toEqual(["fresh"]);
});
it("hands each subscriber a copy it can diff against the next one", () => {
const ws = new FakeSocket();
const { store } = storeWith([ws]);
const seen: CatalogState[] = [];
store.subscribe((s) => seen.push(s));
store.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("doubles the delay per attempt and caps it", () => {
const sockets = Array.from({ length: 8 }, () => new FakeSocket());
const { store, scheduler } = storeWith(sockets);
store.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.start();
sockets[0].drop();
scheduler.runNext();
expect(store.backoff()).toBe(INITIAL_BACKOFF_MS * 2);
sockets[1].open();
expect(store.backoff()).toBe(INITIAL_BACKOFF_MS);
});
});
+54 -10
View File
@@ -7,20 +7,60 @@ export interface CatalogState {
export type CatalogListener = (state: CatalogState) => void;
/** 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<Session[]>;
}
export class CatalogStore {
private state: CatalogState = { sessions: new Map() };
private listeners = new Set<CatalogListener>();
private ws: WebSocket | null = null;
private reconnectTimer: number | null = null;
private backoffMs = 500;
private backoffMs = INITIAL_BACKOFF_MS;
private readonly socket: SocketFactory;
private readonly scheduler: Scheduler;
private readonly refetch: () => Promise<Session[]>;
constructor(opts: CatalogStoreOptions = {}) {
this.socket = opts.socket ?? (() => new WebSocket(eventsWsUrl()));
this.scheduler = opts.scheduler ?? browserScheduler;
this.refetch = opts.refetch ?? listSessions;
}
start(): void {
this.connect();
}
/** Current reconnect delay, for tests asserting the backoff schedule. */
backoff(): number {
return this.backoffMs;
}
stop(): void {
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.scheduler.clearTimer(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.ws) {
@@ -36,12 +76,15 @@ export class CatalogStore {
return () => this.listeners.delete(listener);
}
/** A copy, so a listener can diff it against the previous one. Returning the
* live object meant in-place mutation was invisible and every event forced a
* full re-render. */
snapshot(): CatalogState {
return this.state;
return { sessions: new Map(this.state.sessions) };
}
private connect(): void {
const ws = new WebSocket(eventsWsUrl());
const ws = this.socket();
this.ws = ws;
ws.onmessage = (ev) => {
@@ -55,7 +98,7 @@ export class CatalogStore {
};
ws.onopen = () => {
this.backoffMs = 500;
this.backoffMs = INITIAL_BACKOFF_MS;
};
ws.onclose = () => {
@@ -74,10 +117,10 @@ export class CatalogStore {
private scheduleReconnect(): void {
if (this.reconnectTimer !== null) return;
const delay = Math.min(this.backoffMs, 10_000);
this.reconnectTimer = window.setTimeout(() => {
const delay = Math.min(this.backoffMs, MAX_BACKOFF_MS);
this.reconnectTimer = this.scheduler.setTimer(() => {
this.reconnectTimer = null;
this.backoffMs = Math.min(this.backoffMs * 2, 10_000);
this.backoffMs = Math.min(this.backoffMs * 2, MAX_BACKOFF_MS);
this.connect();
}, delay);
}
@@ -108,7 +151,7 @@ export class CatalogStore {
private async resync(): Promise<void> {
try {
const sessions = await listSessions();
const sessions = await this.refetch();
this.state = {
sessions: new Map(sessions.map((s) => [s.id, s])),
};
@@ -119,6 +162,7 @@ export class CatalogStore {
}
private emit(): void {
for (const fn of this.listeners) fn(this.state);
const snap = this.snapshot();
for (const fn of this.listeners) fn(snap);
}
}
+10
View File
@@ -0,0 +1,10 @@
// One HTML escaper. Previously written four times, in catalog.ts, spawn.ts,
// types.ts and attach.ts.
export function escapeHtml(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { applyModsToChar, cursorSeq, toCtrl } from "./keys.js";
describe("toCtrl", () => {
it("maps letters to their control code, case-insensitively", () => {
expect(toCtrl("a")).toBe("\x01");
expect(toCtrl("A")).toBe("\x01");
expect(toCtrl("c")).toBe("\x03");
expect(toCtrl("[")).toBe("\x1b");
});
it("handles the two specials outside the @-_ range", () => {
expect(toCtrl(" ")).toBe("\x00");
expect(toCtrl("?")).toBe("\x7f");
});
it("passes through anything it has no mapping for", () => {
expect(toCtrl("1")).toBe("1");
expect(toCtrl("é")).toBe("é");
expect(toCtrl("abc")).toBe("abc");
expect(toCtrl("")).toBe("");
});
});
describe("applyModsToChar", () => {
it("composes ctrl and alt, with ESC outermost", () => {
expect(applyModsToChar("a", false, false)).toBe("a");
expect(applyModsToChar("a", true, false)).toBe("\x01");
expect(applyModsToChar("a", false, true)).toBe("\x1ba");
expect(applyModsToChar("a", true, true)).toBe("\x1b\x01");
});
});
describe("cursorSeq", () => {
it("uses the bare CSI form when unmodified", () => {
expect(cursorSeq("A", false, false)).toBe("\x1b[A");
});
it("uses the xterm modifier encoding n = 1 + alt(2) + ctrl(4)", () => {
expect(cursorSeq("A", false, true)).toBe("\x1b[1;3A");
expect(cursorSeq("A", true, false)).toBe("\x1b[1;5A");
expect(cursorSeq("A", true, true)).toBe("\x1b[1;7A");
});
});
+28
View File
@@ -0,0 +1,28 @@
// Terminal key encoding: control characters, meta prefixes, and cursor escape
// sequences. Table-driven and easy to get subtly wrong, so it lives apart from
// the DOM and is tested directly.
export function toCtrl(ch: string): string {
if (ch.length !== 1) return ch;
const upper = ch.toUpperCase().codePointAt(0) ?? 0;
if (upper >= 0x40 && upper <= 0x5f) return String.fromCodePoint(upper & 0x1f);
if (ch === " ") return "\x00";
if (ch === "?") return "\x7f";
return ch;
}
/** Apply pending modifiers to a single typed character: Ctrl → control code,
* Alt → ESC prefix (xterm meta). Both compose (Ctrl+Alt = ESC + control). */
export function applyModsToChar(ch: string, ctrl: boolean, alt: boolean): string {
let out = ctrl ? toCtrl(ch) : ch;
if (alt) out = "\x1b" + out;
return out;
}
/** Cursor/nav-key sequence, promoted to the modified CSI form when Ctrl/Alt are
* pending — `\x1b[1;<n><final>`, n = 1 + alt(2) + ctrl(4) (xterm convention). */
export function cursorSeq(final: string, ctrl: boolean, alt: boolean): string {
if (!ctrl && !alt) return `\x1b[${final}`;
const n = 1 + (alt ? 2 : 0) + (ctrl ? 4 : 0);
return `\x1b[1;${n}${final}`;
}
+89
View File
@@ -0,0 +1,89 @@
import { describe, expect, it } from "vitest";
import {
emptyLayout,
leaves,
locateSession,
openSessions,
removeLeaf,
splitLeaf,
type Tab,
} from "./layout.js";
function tabWithOneLeaf(sessionId: string | null = null): Tab {
const layout = emptyLayout();
const tab = layout.tabs[0];
splitLeaf(tab, "", sessionId, "row", true);
return tab;
}
describe("splitLeaf", () => {
it("seeds an empty tab with a single leaf", () => {
const tab = tabWithOneLeaf("s1");
expect(leaves(tab.root)).toHaveLength(1);
expect(leaves(tab.root)[0].sessionId).toBe("s1");
});
it("splits a leaf in two and returns the new id", () => {
const tab = tabWithOneLeaf("s1");
const target = leaves(tab.root)[0].id;
const fresh = splitLeaf(tab, target, "s2", "row", true);
const ids = leaves(tab.root).map((l) => l.id);
expect(ids).toHaveLength(2);
expect(ids).toContain(fresh);
});
it("honours the side the caller asked for", () => {
const tab = tabWithOneLeaf("s1");
const target = leaves(tab.root)[0].id;
const fresh = splitLeaf(tab, target, "s2", "row", false);
expect(leaves(tab.root)[0].id).toBe(fresh);
});
});
describe("removeLeaf", () => {
it("collapses the parent split into the surviving sibling", () => {
const tab = tabWithOneLeaf("s1");
const first = leaves(tab.root)[0].id;
splitLeaf(tab, first, "s2", "row", true);
removeLeaf(tab, first);
const remaining = leaves(tab.root);
expect(remaining).toHaveLength(1);
expect(remaining[0].sessionId).toBe("s2");
expect(tab.root?.kind).toBe("leaf");
});
it("empties the tab when the last leaf goes", () => {
const tab = tabWithOneLeaf("s1");
removeLeaf(tab, leaves(tab.root)[0].id);
expect(tab.root).toBeNull();
});
});
describe("locateSession / openSessions", () => {
it("finds the tab and leaf showing a session", () => {
const layout = emptyLayout();
const tab = layout.tabs[0];
splitLeaf(tab, "", "s1", "row", true);
const hit = locateSession(layout, "s1");
expect(hit?.tab.id).toBe(tab.id);
expect(hit?.leaf.sessionId).toBe("s1");
expect(locateSession(layout, "nope")).toBeNull();
});
it("reports every open session once", () => {
const layout = emptyLayout();
const tab = layout.tabs[0];
splitLeaf(tab, "", "s1", "row", true);
const first = leaves(tab.root)[0].id;
splitLeaf(tab, first, "s2", "row", true);
expect(openSessions(layout)).toEqual(new Set(["s1", "s2"]));
});
});
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { longestCommonPrefix, splitPath } from "./paths.js";
describe("splitPath", () => {
it("splits on the last slash, keeping it with the directory", () => {
expect(splitPath("/home/n/wo")).toEqual({ dir: "/home/n/", prefix: "wo" });
expect(splitPath("/home/n/")).toEqual({ dir: "/home/n/", prefix: "" });
});
it("treats a slash-free value as all prefix", () => {
expect(splitPath("work")).toEqual({ dir: "", prefix: "work" });
expect(splitPath("")).toEqual({ dir: "", prefix: "" });
});
});
describe("longestCommonPrefix", () => {
it("returns the shared head", () => {
expect(longestCommonPrefix(["maestro", "maestro-web"])).toBe("maestro");
expect(longestCommonPrefix(["abc"])).toBe("abc");
});
it("is empty when nothing is shared", () => {
expect(longestCommonPrefix(["abc", "xyz"])).toBe("");
expect(longestCommonPrefix([])).toBe("");
});
it("preserves on-disk casing rather than folding it", () => {
expect(longestCommonPrefix(["Alpha", "alpha"])).toBe("");
});
});
+21
View File
@@ -0,0 +1,21 @@
// Path splitting and completion arithmetic for the working-directory input.
export function splitPath(value: string): { dir: string; prefix: string } {
const slash = value.lastIndexOf("/");
if (slash === -1) return { dir: "", prefix: value };
return { dir: value.slice(0, slash + 1), prefix: value.slice(slash + 1) };
}
/** Longest common prefix of a list of strings (case-sensitive, preserving the
* actual on-disk casing). */
export function longestCommonPrefix(items: string[]): string {
if (items.length === 0) return "";
let lcp = items[0];
for (const s of items.slice(1)) {
let i = 0;
while (i < lcp.length && i < s.length && lcp[i] === s[i]) i++;
lcp = lcp.slice(0, i);
if (lcp === "") break;
}
return lcp;
}
+64
View File
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";
import { hydrate } from "./persistence.js";
import { leaves } from "./layout.js";
describe("hydrate", () => {
it("rejects anything that is not a tab-bearing object", () => {
expect(hydrate(null)).toBeNull();
expect(hydrate("nope")).toBeNull();
expect(hydrate({})).toBeNull();
expect(hydrate({ tabs: [] })).toBeNull();
expect(hydrate({ tabs: "no" })).toBeNull();
});
it("rebuilds tabs and re-issues ids rather than trusting stored ones", () => {
const layout = hydrate({
tabs: [{ id: "old", title: "Work", root: { kind: "leaf", id: "l1", sessionId: "s1" } }],
activeTabId: "old",
});
expect(layout).not.toBeNull();
expect(layout!.tabs).toHaveLength(1);
expect(layout!.tabs[0].title).toBe("Work");
expect(layout!.tabs[0].id).not.toBe("old");
expect(layout!.activeTabId).toBe(layout!.tabs[0].id);
expect(leaves(layout!.tabs[0].root)[0].sessionId).toBe("s1");
});
it("carries the focused leaf across the id reissue", () => {
const layout = hydrate({
tabs: [
{
id: "t",
root: {
kind: "split",
dir: "row",
a: { kind: "leaf", id: "l1", sessionId: "s1" },
b: { kind: "leaf", id: "l2", sessionId: "s2" },
},
focusedLeafId: "l2",
},
],
activeTabId: "t",
});
const tab = layout!.tabs[0];
const focused = leaves(tab.root).find((l) => l.id === tab.focusedLeafId);
expect(focused?.sessionId).toBe("s2");
});
it("falls back to a default title and the first tab as active", () => {
const layout = hydrate({ tabs: [{ id: "a" }, { id: "b" }], activeTabId: "missing" });
expect(layout!.tabs[0].title).toBe("Tab 1");
expect(layout!.activeTabId).toBe(layout!.tabs[0].id);
});
it("drops a malformed split branch instead of failing the whole layout", () => {
const layout = hydrate({
tabs: [{ id: "t", root: { kind: "split", dir: "row", a: null, b: { kind: "leaf", id: "l", sessionId: "s" } } }],
activeTabId: "t",
});
expect(leaves(layout!.tabs[0].root).map((l) => l.sessionId)).toEqual(["s"]);
});
});
+1 -1
View File
@@ -37,7 +37,7 @@ export function loadLayout(): Layout | null {
}
}
function hydrate(raw: unknown): Layout | null {
export function hydrate(raw: unknown): Layout | null {
if (!raw || typeof raw !== "object") return null;
const r = raw as { tabs?: unknown; activeTabId?: unknown };
if (!Array.isArray(r.tabs) || r.tabs.length === 0) return null;
+1 -8
View File
@@ -1,3 +1,4 @@
import { escapeHtml } from "./html.js";
import { createSession, getDaemonInfo, recentDirs, gitRoot } from "./api.js";
import { attachDirAutocomplete, type DirAutocompleteHandle } from "./dirAutocomplete.js";
import { generateName } from "./names.js";
@@ -425,11 +426,3 @@ export function openSpawnModal(prefill?: SpawnPrefill): void {
});
}
function escapeHtml(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest";
import { buildTree, mergeLinear, type TreeFolder, type TreeNode } from "./tree.js";
import type { Session } from "./types.js";
function session(id: string, cwd: string, command = "bash"): Session {
return {
id,
cwd,
command,
env: {},
metadata: {},
status: "Running",
created_at: "2026-08-22T00:00:00Z",
} as Session;
}
/** Folder names at one level, in render order. */
function names(node: TreeNode): string[] {
if (node.kind === "leaf") return [];
return node.children.map((c) => (c.kind === "folder" ? c.name : "leaf"));
}
describe("buildTree", () => {
it("groups sessions under their directory", () => {
const root = buildTree(
[session("a", "/home/n/work"), session("b", "/home/n/work")],
"/home/n",
"",
) as TreeFolder;
expect(names(root)).toEqual(["~/work"]);
const folder = root.children[0] as TreeFolder;
expect(folder.children).toHaveLength(2);
});
it("collapses a linear chain into one folder", () => {
const root = buildTree([session("a", "/home/n/git/naps62/maestro")], "/home/n", "") as TreeFolder;
expect(names(root)).toEqual(["~/git/naps62/maestro"]);
});
it("stops collapsing where a directory branches", () => {
const root = buildTree(
[session("a", "/home/n/git/one"), session("b", "/home/n/git/two")],
"/home/n",
"",
) as TreeFolder;
expect(names(root)).toEqual(["~/git"]);
const git = root.children[0] as TreeFolder;
expect(names(git).sort()).toEqual(["one", "two"]);
});
it("sorts folders before leaves, then by name", () => {
const root = buildTree(
[session("loose", ""), session("nested", "/home/n/work")],
"/home/n",
"",
) as TreeFolder;
expect(root.children[0].kind).toBe("folder");
expect(root.children[1].kind).toBe("leaf");
});
it("filters on both session name and directory", () => {
const sessions = [session("a", "/home/n/alpha", "claude"), session("b", "/home/n/beta", "bash")];
const byDir = buildTree(sessions, "/home/n", "alpha") as TreeFolder;
expect(names(byDir)).toEqual(["~/alpha"]);
const byCommand = buildTree(sessions, "/home/n", "claude") as TreeFolder;
expect(names(byCommand)).toEqual(["~/alpha"]);
const noMatch = buildTree(sessions, "/home/n", "zzz") as TreeFolder;
expect(noMatch.children).toEqual([]);
});
it("ignores case and surrounding whitespace in the filter", () => {
const root = buildTree([session("a", "/home/n/Alpha")], "/home/n", " ALPHA ") as TreeFolder;
expect(root.children).toHaveLength(1);
});
});
describe("mergeLinear", () => {
it("keeps the deepest path so collapse state survives growth", () => {
const folder: TreeFolder = {
kind: "folder",
name: "a",
path: "a",
children: [{ kind: "folder", name: "b", path: "a/b", children: [] }],
};
const merged = mergeLinear(folder);
expect(merged.name).toBe("a/b");
expect(merged.path).toBe("a/b");
});
});
+84
View File
@@ -0,0 +1,84 @@
// Directory grouping for the session catalog. Pure: no DOM, no module state,
// so it can be tested directly.
import type { Session } from "./types.js";
import { abbreviateCwd, sessionCwd, sessionName } from "./types.js";
export interface TreeFolder {
kind: "folder";
name: string;
path: string;
children: TreeNode[];
}
export interface TreeLeaf {
kind: "leaf";
session: Session;
}
export type TreeNode = TreeFolder | TreeLeaf;
export function compareNodes(a: TreeNode, b: TreeNode): number {
if (a.kind !== b.kind) return a.kind === "folder" ? -1 : 1;
const an = a.kind === "folder" ? a.name : sessionName(a.session);
const bn = b.kind === "folder" ? b.name : sessionName(b.session);
return an.localeCompare(bn);
}
export function buildTree(sessions: Session[], home: string | undefined, filter: string): TreeNode {
const root: TreeFolder = { kind: "folder", name: "", path: "", children: [] };
const lc = filter.trim().toLowerCase();
for (const s of sessions) {
const cwd = sessionCwd(s);
const dir = cwd ? abbreviateCwd(cwd, home) : "";
if (lc) {
const haystack = `${sessionName(s)} ${dir}`.toLowerCase();
if (!haystack.includes(lc)) continue;
}
const parts = dir ? dir.split("/").filter(Boolean) : [];
let cursor = root;
for (const part of parts) {
const path = cursor.path ? `${cursor.path}/${part}` : part;
let next = cursor.children.find(
(n): n is TreeFolder => n.kind === "folder" && n.name === part,
);
if (!next) {
next = { kind: "folder", name: part, path, children: [] };
cursor.children.push(next);
}
cursor = next;
}
cursor.children.push({ kind: "leaf", session: s });
}
const sortRec = (n: TreeFolder) => {
n.children.sort(compareNodes);
for (const c of n.children) if (c.kind === "folder") sortRec(c);
};
sortRec(root);
// Collapse linear directory chains so `~/git.naps.pt/naps62/maestro` reads as
// one compact folder rather than four nested ones.
root.children = root.children.map((c) => (c.kind === "folder" ? mergeLinear(c) : c));
return root;
}
/** Fold a folder with a single folder-child into one node (`a` + `b` → `a/b`),
* repeating down the chain, then recurse into the surviving branches. The merged
* node keeps the deepest path so collapse/expand state stays stable as it grows. */
export function mergeLinear(folder: TreeFolder): TreeFolder {
let cur = folder;
while (cur.children.length === 1 && cur.children[0].kind === "folder") {
const child = cur.children[0];
cur = {
kind: "folder",
name: `${cur.name}/${child.name}`,
path: child.path,
children: child.children,
};
}
cur.children = cur.children.map((c) =>
c.kind === "folder" ? mergeLinear(c) : c,
);
return cur;
}
+2 -8
View File
@@ -1,3 +1,5 @@
import { escapeHtml } from "./html.js";
// Mirror of `maestro-protocol` JSON shapes. Keep in sync with
// crates/maestro-protocol/src/lib.rs.
@@ -151,11 +153,3 @@ export function abbreviateFolderName(name: string): string {
.join("/");
return `<span class="folder-stem">${escapeHtml(stem)}/</span>${escapeHtml(last)}`;
}
function escapeHtml(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}