import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent"; import { initTheme } from "@earendil-works/pi-coding-agent"; import { type Component, CURSOR_MARKER, type OverlayHandle, type OverlayOptions, stripTerminalSequences, type TUI, type TuiMouseEvent, visibleWidth, } from "@earendil-works/pi-tui"; import { beforeAll, describe, expect, it, vi } from "vitest"; import { Look } from "../src/look.ts"; import { EphemletPanel, PanelHost, panelGeometry } from "../src/panel.ts"; import { EphemletStore } from "../src/store.ts"; import { plainTheme as theme } from "./theme.ts"; /** Column of a glyph in a plain-text row. */ const column = (line: string, text: string) => visibleWidth(line.slice(0, line.indexOf(text))); const lineWith = (lines: string[], text: string) => lines.find((line) => line.includes(text)) ?? ""; const noActions = { changed() {}, close() {}, save() {}, hide() {}, answered() {}, }; beforeAll(() => initTheme("dark", false)); function mouse( x: number, y: number, type: TuiMouseEvent["type"] = "click", ): TuiMouseEvent { return { x, y, screenX: x, screenY: y, width: 60, height: 30, type, button: "left", shift: false, alt: false, ctrl: false, }; } function handle(overrides: Partial = {}): OverlayHandle { return { hide() {}, setHidden() {}, isHidden: () => false, focus() {}, unfocus() {}, isFocused: () => false, getBounds: () => undefined, ...overrides, } as OverlayHandle; } function fixture() { const store = new EphemletStore(() => {}); const terminal = { columns: 120, rows: 32 }; const tui = { terminal, requestRender() {} } as unknown as TUI; const closed: string[] = []; const saved: string[] = []; let hidden = 0; const answered: string[] = []; const panel = new EphemletPanel( store, tui, theme, { changed: () => panel.refresh(), close: (id) => { closed.push(id); store.delete(id); panel.refresh(); }, save: (id) => saved.push(id), hide: () => { hidden++; store.view(store.selected, false); }, answered: (id, field) => answered.push(`${id}/${field}`), }, () => new Look(theme, undefined, "unicode"), ); const put = (source: string) => { const record = store.put({ title: "Report", purpose: "Progress", source }); store.view(record.id, true); panel.refresh(); return record; }; const host = (ctx: ExtensionContext) => new PanelHost( store, () => ctx, noActions, () => "unicode", ); return { store, terminal, tui, panel, put, host, closed, saved, answered, hidden: () => hidden, }; } function widgetContext(tui: TUI, extra: Record = {}) { let widget: (Component & { dispose?(): void }) | undefined; let placement: string | undefined; const ctx = { mode: "tui", ui: { setWidget( _key: string, factory: ((tui: TUI, theme: Theme) => typeof widget) | undefined, options?: { placement?: string }, ) { widget?.dispose?.(); widget = factory?.(tui, theme); placement = options?.placement; }, ...extra, }, } as unknown as ExtensionContext; return { ctx, widget: () => widget, placement: () => placement }; } describe("ephemlet responsive overlay", () => { it("positions landscape right and portrait top, including small terminals", () => { expect(panelGeometry(120, 32)).toEqual({ anchor: "top-right", width: 54, height: 28, }); expect(panelGeometry(60, 50)).toEqual({ anchor: "top-left", width: 60, height: 24, }); expect(panelGeometry(2, 2)).toEqual({ anchor: "top-left", width: 2, height: 1, }); }); it("renders Markdown within resized bounds and scrolls by keyboard", () => { const f = fixture(); f.put(Array.from({ length: 60 }, (_, i) => `Line ${i}`).join("\n\n")); expect(f.panel.render(54).join("\n")).toContain("Line 0"); f.panel.handleInput("\x1b[6~"); expect(f.panel.render(54).join("\n")).not.toContain("Line 0"); f.panel.handleInput("\x1b[5~"); expect(f.panel.render(54).join("\n")).toContain("Line 0"); f.terminal.columns = 30; f.terminal.rows = 50; const lines = f.panel.render(30); expect(lines.length).toBeLessThanOrEqual(24); expect(lines.every((line) => visibleWidth(line) <= 30)).toBe(true); }); it("switches ephemlets by keyboard/mouse and hides without deleting", () => { const f = fixture(); const first = f.put("first"); const second = f.put("second"); expect(f.panel.render(54).join("\n")).toContain("second"); f.panel.handleInput("\x1b[1;3D"); expect(f.store.selected).toBe(first.id); const header = f.panel.render(54)[0] ?? ""; expect(header).toContain("●○"); f.panel.handleMouse(mouse(column(header, "●○") + 1, 0)); expect(f.store.selected).toBe(second.id); f.panel.handleInput("\x1b"); expect(f.hidden()).toBe(1); expect(f.store.records.size).toBe(2); }); it("saves and deletes by shortcut or header click", () => { const f = fixture(); const record = f.put("report"); const header = f.panel.render(54)[0] ?? ""; expect(header).toContain("⤓ ✕"); f.panel.handleInput("\x13"); expect(f.saved).toEqual([record.id]); expect(f.store.records.size).toBe(1); f.panel.handleMouse(mouse(column(header, "⤓"), 0)); expect(f.saved).toEqual([record.id, record.id]); f.panel.handleInput("\t"); f.panel.handleInput("\r"); expect(f.closed).toEqual([]); f.panel.handleInput("\x17"); expect(f.closed).toEqual([record.id]); expect(f.store.records.size).toBe(0); }); it("routes the delete icon cell to deletion, not Save", () => { const f = fixture(); const record = f.put("report"); const header = f.panel.render(54)[0] ?? ""; f.panel.handleMouse(mouse(column(header, "✕"), 0)); expect(f.closed).toEqual([record.id]); expect(f.saved).toEqual([]); }); it("toggles checklist items by keyboard focus and click without scrolling away", () => { const f = fixture(); const record = f.store.put({ title: "Plan", purpose: "Steer", source: Array.from({ length: 40 }, (_, i) => `Line ${i}`).join("\n\n"), fields: [ { id: "plan", type: "checklist", items: [ { id: "a", label: "Alpha\x1b[2J" }, { id: "b", label: "Beta", checked: true }, ], }, ], }); f.store.view(record.id, true); f.panel.refresh(); expect(f.panel.render(54).join("\n")).not.toContain("Alpha"); expect(f.panel.render(54).join("\n")).not.toMatch(/instant|next turn/); f.panel.handleInput("\t"); let frame = f.panel.render(54).join("\n"); expect(frame).toContain("☐ Alpha"); expect(frame).not.toContain("\x1b[2J"); f.panel.handleInput(" "); f.panel.handleInput("\x1b[Z"); f.panel.handleInput("\r"); expect(f.store.get(record.id).answers).toEqual({ plan: { a: true, b: false }, }); frame = f.panel.render(54).join("\n"); expect(frame).toContain("◷ unread"); // Unticking an item the agent had checked renders as a veto marked as yours. expect(lineWith(f.panel.render(54), "Beta")).toContain("☐ Beta · you"); expect(frame).toContain("1/2"); const lines = f.panel.render(54); const row = lines.findIndex((line) => line.includes("Alpha")); f.panel.handleMouse(mouse(4, row)); expect(f.store.get(record.id).answers["plan"]?.["a"]).toBe(false); f.store.seen(record.id); expect(f.panel.render(54)[0]).toContain("✔ read"); }); it("renders questions, keeps single answers exclusive and reports answers", () => { const f = fixture(); const record = f.store.put({ title: "Decide", purpose: "Ask", source: "# Decide", fields: [ { id: "approach", type: "choice", label: "Approach", options: [ { id: "a", label: "Alpha" }, { id: "b", label: "Beta" }, ], }, { id: "ship", type: "confirm", label: "Ship it?" }, ], }); f.store.view(record.id, true); f.panel.refresh(); let lines = f.panel.render(54); expect(lineWith(lines, "Approach")).toContain("needs you"); expect(lineWith(lines, "Ship it?")).toContain("needs you"); // Delivery is visible before answering: confirm interrupts, choice waits a turn. expect(lineWith(lines, "Ship it?")).toMatch(/↯ instant $/); expect(lineWith(lines, "Approach")).toMatch(/⇢ next turn $/); expect(lines.join("\n")).toContain("○ Alpha"); expect(lineWith(lines, "Yes")).toMatch(/^ {2}Yes {3}No /); f.panel.handleInput("\t"); f.panel.handleInput(" "); f.panel.handleInput("\t"); f.panel.handleInput(" "); f.panel.handleInput(" "); lines = f.panel.render(54); expect(lines.join("\n")).toContain("○ Alpha"); expect(lines.join("\n")).toContain("◉ Beta"); expect(lineWith(lines, "Approach")).not.toContain("needs you"); expect(f.answered).toEqual([ `${record.id}/approach`, `${record.id}/approach`, ]); expect(lines[0]).toContain("◷ unread"); f.store.sent.set(record.id, 2); expect(f.panel.render(54)[0]).toContain("✓ sent"); // Confirm answers are clickable segments within one row. lines = f.panel.render(54); const row = lines.findIndex((line) => line.includes("Yes")); f.panel.handleMouse(mouse(column(lines[row] ?? "", "No"), row)); expect(f.store.get(record.id).answers["ship"]).toEqual({ yes: false, no: true, }); }); it("pins a needs-you marker for open questions out of view and jumps to them", () => { const f = fixture(); const record = f.store.put({ title: "Plan", purpose: "Steer", source: Array.from({ length: 40 }, (_, i) => `Line ${i}`).join("\n\n"), fields: [{ id: "ship", type: "confirm", label: "Ship it?" }], }); f.store.view(record.id, true); let lines = f.panel.render(54); const marker = lines.findIndex((line) => line.includes("↓ 1 needs you")); expect(marker).toBe(lines.length - 2); expect(lines.join("\n")).not.toContain("Yes"); f.panel.handleMouse(mouse(3, marker)); lines = f.panel.render(54); expect(lines.join("\n")).toContain("Ship it?"); expect(lines.join("\n")).not.toContain("\u2193"); expect(lineWith(lines, "Yes")).toMatch(/Yes {3}No/); f.panel.handleInput(" "); expect(f.store.get(record.id).answers["ship"]).toEqual({ yes: true, no: false, }); expect(f.panel.render(54).join("\n")).not.toContain("needs you"); }); it("sends the first tab to an open question and starts new revisions at the top", () => { const f = fixture(); const record = f.store.put({ title: "Plan", purpose: "Steer", source: "# Plan", fields: [ { id: "plan", type: "checklist", items: [{ id: "a", label: "Alpha" }] }, { id: "pick", type: "choice", options: [ { id: "x", label: "Xray" }, { id: "y", label: "Yankee" }, ], }, ], }); f.store.view(record.id, true); f.panel.render(54); f.panel.handleInput("\t"); f.panel.handleInput(" "); expect(f.store.get(record.id).answers).toEqual({ pick: { x: true, y: false }, }); f.panel.handleInput("\x1b[6~"); const next = f.store.put({ ...f.store.get(record.id), expectedRevision: 1, source: Array.from({ length: 40 }, (_, i) => `Line ${i}`).join("\n\n"), }); expect(next.revision).toBe(2); expect(f.panel.render(54).join("\n")).toContain("Line 0"); }); it("edits text answers inline, submits on enter and cancels on escape", () => { const f = fixture(); const record = f.store.put({ title: "Ask", purpose: "Ask", source: "# Ask", fields: [ { id: "why", type: "text", label: "Why?", placeholder: "One sentence", }, ], }); f.store.view(record.id, true); let lines = f.panel.render(54); expect(lineWith(lines, "Why?")).toMatch(/needs you.*\u21e2 next turn $/); expect(lineWith(lines, "One sentence")).toContain("\u270e One sentence"); f.panel.handleInput("\t"); f.panel.handleInput("\r"); expect(f.panel.render(54).at(-1)).toContain("enter submit"); for (const key of "Faster") f.panel.handleInput(key); f.panel.handleInput("\x1b"); expect(f.store.get(record.id).texts).toEqual({}); expect(f.hidden()).toBe(0); f.panel.handleInput("\r"); for (const key of "Faster") f.panel.handleInput(key); f.panel.handleInput("\r"); expect(f.store.get(record.id).texts).toEqual({ why: "Faster" }); expect(f.answered).toEqual([`${record.id}/why`]); lines = f.panel.render(54); expect(lineWith(lines, "Faster")).toContain("\u270e Faster"); expect(lineWith(lines, "Why?")).not.toContain("needs you"); f.store.waiting.set(record.id, new Set(["why"])); expect(lineWith(f.panel.render(54), "Why?")).toMatch( /\u29d7 agent waiting $/, ); }); it("wraps text answers and the inline editor inside painted rows without losing the cursor", () => { // Every painted segment is bracketed, so unpainted cells are visible leftovers. const painted = { ...theme, style: (text: string) => `\u27e6${text}\u27e7`, } as unknown as Theme; const unpainted = (line: string) => stripTerminalSequences(line.replace(/\u27e6[^\u27e7]*\u27e7/g, "")); const words = "wrap these words ".repeat(12); for (let length = 20; length <= 110; length++) { const store = new EphemletStore(() => {}); const tui = { terminal: { columns: 120, rows: 32 }, requestRender() {}, } as unknown as TUI; const panel = new EphemletPanel( store, tui, painted, noActions, () => new Look(painted, undefined, "unicode"), ); const record = store.put({ title: "Ask", purpose: "Ask", source: "# Ask", fields: [{ id: "why", type: "text", label: "Why?" }], }); store.view(record.id, true); panel.render(54); panel.handleInput("\t"); panel.handleInput("\r"); for (const key of words.slice(0, length)) panel.handleInput(key); const editing = panel.render(54); const rows = editing.filter((line) => line.includes("\u270e")); const field = editing.slice( editing.indexOf(rows[0] ?? ""), editing.indexOf(rows[0] ?? "") + Math.ceil(length / 40) + 2, ); expect(field.some((line) => line.includes(CURSOR_MARKER))).toBe(true); expect( field.some((line) => /\x1b_pi:fc\x07[^\x1b]+\x1b_pi:\/fc\x07/.test(line), ), ).toBe(true); for (const line of field) { expect( visibleWidth(line.replace(/[\u27e6\u27e7]/g, "")), ).toBeLessThanOrEqual(54); if (line.includes("\u27e6")) expect(unpainted(line)).toBe(""); } panel.handleInput("\r"); const text = panel .render(54) .map((line) => stripTerminalSequences(line).replace(/[\u27e6\u27e7\u2502]/g, ""), ) .join(" "); expect(text.replace(/\s+/g, " ")).toContain( words.slice(0, length).trim().replace(/\s+/g, " "), ); expect(text).not.toContain("\u2026"); } }); it("tracks hover only over answer rows and re-renders only on change", () => { const f = fixture(); const record = f.store.put({ title: "Plan", purpose: "Steer", source: "# Plan", fields: [ { id: "plan", type: "checklist", items: [{ id: "a", label: "Alpha" }] }, ], }); f.store.view(record.id, true); const lines = f.panel.render(54); const row = lines.findIndex((line) => line.includes("Alpha")); expect(f.panel.handleMouse(mouse(4, row, "move"))).toEqual({ handled: true, render: true, }); expect(f.panel.handleMouse(mouse(6, row, "move"))).toEqual({ handled: true, }); expect(f.panel.handleMouse(mouse(4, 0, "move"))).toEqual({ handled: true, render: true, }); expect(f.store.get(record.id).answerRevision).toBe(0); }); it("returns only actually rendered bounded views and marks revisions stale", () => { const f = fixture(); const record = f.put("# Current\nRendered report"); expect(f.panel.getView(record.id)).toEqual({ available: false, reason: "Never rendered", }); f.panel.render(54); const view = f.panel.getView(record.id); expect(view).toMatchObject({ available: true, revision: record.revision, width: 54, stale: false, }); if (view.available) expect(view.plainText).toContain("Rendered report"); f.store.put({ ...record, expectedRevision: 1, source: "changed" }); expect(f.panel.getView(record.id)).toMatchObject({ available: true, stale: true, }); }); it("keeps compact presence above editor without mounting an overlay", () => { const f = fixture(); const record = f.put("report"); f.store.view(record.id, false); const showOverlay = vi.fn(); f.tui.showOverlay = showOverlay; const w = widgetContext(f.tui); const host = f.host(w.ctx); try { host.refresh(); expect(showOverlay).not.toHaveBeenCalled(); expect(w.placement()).toBe("aboveEditor"); expect(w.widget()?.render(60).join("\n")).toBe( " ● Ephemlets 1 · alt+e expand", ); f.store.put({ title: "Ask", purpose: "Ask", source: "?", fields: [{ id: "go", type: "confirm", label: "Go?" }], }); expect(w.widget()?.render(60).join("\n")).toBe( " ● Ephemlets 2 1 needs you · alt+e expand", ); expect(host.getView(record.id)).toEqual({ available: false, reason: "Never rendered", }); } finally { host.dispose(); } }); it("cleans failed widget registration and allows retry", () => { const f = fixture(); f.put("report"); const mounted: Component[] = []; const hide = vi.fn(); const notify = vi.fn(); let calls = 0; f.tui.showOverlay = (component) => { mounted.push(component); return handle({ hide }); }; const ctx = { mode: "tui", ui: { notify, setWidget: ( _key: string, factory: ((tui: TUI, theme: Theme) => unknown) | undefined, ) => { if (!factory) return; factory(f.tui, theme); if (++calls === 1) throw new Error("Widget registration failed"); }, }, } as unknown as ExtensionContext; const host = f.host(ctx); try { host.refresh(); expect(notify).toHaveBeenCalledWith( "Ephemlet panel: Error: Widget registration failed", "error", ); expect(hide).toHaveBeenCalledTimes(1); expect(mounted[0]?.render(54)).toEqual([]); host.refresh(); expect(calls).toBe(2); expect(mounted[1]?.render(54).length).toBeGreaterThan(0); host.dispose(); expect(mounted[1]?.render(54)).toEqual([]); expect(hide).toHaveBeenCalledTimes(2); } finally { host.dispose(); } }); it("hides through overlay handle rather than deleting/reloading", () => { const f = fixture(); f.put("report"); let isHidden = false; let options: OverlayOptions | undefined; f.tui.showOverlay = (_component, nextOptions) => { options = nextOptions; return handle({ setHidden(value: boolean) { isHidden = value; }, isHidden: () => isHidden, }); }; const w = widgetContext(f.tui); const setWidget = vi.spyOn(w.ctx.ui, "setWidget"); const host = f.host(w.ctx); try { host.refresh(); f.store.view(f.store.selected, false); host.refresh(); expect(isHidden).toBe(true); f.store.view(f.store.selected, true); host.refresh(true); expect(isHidden).toBe(false); expect(setWidget).toHaveBeenCalledTimes(1); expect(options?.anchor).toBe("top-right"); f.terminal.columns = 40; f.terminal.rows = 50; expect(options?.anchor).toBe("top-left"); expect(options?.width).toBe(40); } finally { host.dispose(); } }); });