repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/notes/__tests__/harness.test.ts
RawFile outline
- t line 7
- extensionPath line 9
- customEntries line 13
- type line 17
- customType line 18
- data line 19
- uiArgs line 26
- latestWidget line 34
- renderLatestWidget line 41
- render line 51
- noteCommand line 58
- afterEach line 64
- notes pi-test-harness line 70
- loads in real Pi extension runtime and registers command plus shortcut line 71
- renders compact count and last note after add line 81
- renders widget at column zero in Pi line 91
- toggles expanded widget with slash command and shortcut line 98
- shows compact widget on session_start when current branch has pending notes line 119
- restores notes after tree navigation line 138
- offers to carry pending notes into a new session line 168
- discards pending notes when new-session carry is rejected line 198
- leaves widget hidden and notifies when toggling with no notes line 218
- removes one note and clears widget when none remain line 226
- confirms before clearing all pending notes line 239
- keeps notes when clear confirmation is rejected line 259
- edits note text and keeps old text on cancel or whitespace save line 273
- unknown ids do not mutate state line 312
- sends exact note text when idle and removes it line 322
- queues send as follow-up when busy line 342
- unknown send id does not send or mutate line 370
- autocompletes subcommands and pending note ids with previews line 385
- replay uses only entries returned by the current branch line 421
- replays add, edit, remove, and clear events in order line 439
- ignores malformed entries and invalid edits or removes line 477
- appends notes-state entries through commands line 510
import { fileURLToPath } from "node:url";
import { Text } from "@earendil-works/pi-tui";
import { afterEach, describe, expect, it } from "vitest";
import { createTestSession, type TestSession } from "../../../test/harness";
import { __test } from "../index.ts";
let t: TestSession | undefined;
function extensionPath(): string {
return fileURLToPath(new URL("../index.ts", import.meta.url));
}
function customEntries(kind: string): Array<Record<string, unknown>> {
if (!t) throw new Error("missing test session");
return (
t.session.sessionManager.getEntries() as Array<{
type: string;
customType?: string;
data?: Record<string, unknown>;
}>
)
.filter((entry) => entry.type === "custom" && entry.customType === kind)
.map((entry) => entry.data ?? {});
}
function uiArgs(method: string): unknown[][] {
return (
t?.events.ui
.filter((call) => call.method === method)
.map((call) => call.args) ?? []
);
}
function latestWidget(): unknown {
return uiArgs("setWidget")
.filter((args) => args[0] === "notes")
.map((args) => args[1])
.at(-1);
}
function renderLatestWidget(width = 80): string[] | undefined {
const widget = uiArgs("setWidget")
.filter((args) => args[0] === "notes")
.map((args) => args[1])
.at(-1);
if (!widget) return undefined;
if (Array.isArray(widget)) {
return widget.flatMap((line) => new Text(line, 1, 0).render(width));
}
if (typeof widget === "function") {
return (widget({}, {}) as { render(width: number): string[] }).render(
width,
);
}
throw new Error("unknown widget shape");
}
async function noteCommand(args: string): Promise<void> {
const command = t?.session.extensionRunner.extensions[0].commands.get("note");
if (!command || !t) throw new Error("missing note command");
await command.handler(args, t.session.extensionRunner.createCommandContext());
}
afterEach(() => {
__test.takeNewSessionNotes();
t?.dispose();
t = undefined;
});
describe("notes pi-test-harness", () => {
it("loads in real Pi extension runtime and registers command plus shortcut", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
const [extension] = t.session.extensionRunner.extensions;
expect(extension.path).toBe(extensionPath());
expect([...extension.commands.keys()]).toEqual(["note"]);
expect([...extension.tools.keys()]).toEqual([]);
expect(extension.shortcuts.has("alt+n")).toBe(true);
});
it("renders compact count and last note after add", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
await noteCommand("add first note");
await noteCommand("add second note");
expect(renderLatestWidget()).toEqual([
" 2 notes · alt+n expand · last: second note",
]);
});
it("renders widget at column zero in Pi", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
await noteCommand("add first note");
expect(renderLatestWidget()?.[0]).toMatch(/^/u);
});
it("toggles expanded widget with slash command and shortcut", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
await noteCommand("add first note");
await noteCommand("add second note");
await noteCommand("");
expect(renderLatestWidget()).toEqual([
" notes · 2",
" 1 first note",
" 2 second note",
]);
const shortcut =
t.session.extensionRunner.extensions[0].shortcuts.get("alt+n");
await shortcut.handler(t.session.extensionRunner.createCommandContext());
expect(renderLatestWidget()).toEqual([
" 2 notes · alt+n expand · last: second note",
]);
});
it("shows compact widget on session_start when current branch has pending notes", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
(t.session.sessionManager as any).appendCustomEntry("notes-state", {
op: "add",
id: 7,
text: "restored note",
createdAt: 1,
});
await t.session.extensionRunner.emit({
type: "session_start",
reason: "resume",
});
expect(renderLatestWidget()).toEqual([
" 1 notes · alt+n expand · last: restored note",
]);
});
it("restores notes after tree navigation", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
await noteCommand("add abandoned note");
const manager = t.session.sessionManager as any;
manager.resetLeaf();
manager.appendCustomEntry("notes-state", {
op: "add",
id: 7,
text: "target note",
createdAt: 1,
});
await t.session.extensionRunner.emit({
type: "session_tree",
oldLeafId: "old",
newLeafId: manager.getLeafId(),
});
expect(renderLatestWidget()).toEqual([
" 1 notes · alt+n expand · last: target note",
]);
await noteCommand("add next note");
expect(customEntries("notes-state").at(-1)).toEqual({
op: "add",
id: 8,
text: "next note",
createdAt: expect.any(Number),
});
});
it("offers to carry pending notes into a new session", async () => {
t = await createTestSession({
extensions: [extensionPath()],
mockUI: { confirm: true },
});
await noteCommand("add carried note");
await t.session.extensionRunner.emit({
type: "session_shutdown",
reason: "new",
});
(t.session.sessionManager as any).newSession();
await t.session.extensionRunner.emit({
type: "session_start",
reason: "new",
});
expect(uiArgs("confirm").at(-1)).toEqual([
"Carry notes?",
"Copy 1 pending notes into the new session?",
]);
expect(customEntries("notes-state")).toEqual([
{
op: "add",
id: 1,
text: "carried note",
createdAt: expect.any(Number),
},
]);
});
it("discards pending notes when new-session carry is rejected", async () => {
t = await createTestSession({
extensions: [extensionPath()],
mockUI: { confirm: false },
});
await noteCommand("add old note");
await t.session.extensionRunner.emit({
type: "session_shutdown",
reason: "new",
});
(t.session.sessionManager as any).newSession();
await t.session.extensionRunner.emit({
type: "session_start",
reason: "new",
});
expect(customEntries("notes-state")).toEqual([]);
expect(latestWidget()).toBeUndefined();
});
it("leaves widget hidden and notifies when toggling with no notes", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
await noteCommand("");
expect(uiArgs("notify").at(-1)).toEqual(["No pending notes", "info"]);
expect(latestWidget()).toBeUndefined();
});
it("removes one note and clears widget when none remain", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
await noteCommand("add first note");
await noteCommand("rm 1");
expect(customEntries("notes-state").at(-1)).toEqual({
op: "remove",
id: 1,
removedAt: expect.any(Number),
});
expect(latestWidget()).toBeUndefined();
});
it("confirms before clearing all pending notes", async () => {
t = await createTestSession({
extensions: [extensionPath()],
mockUI: { confirm: true },
});
await noteCommand("add first note");
await noteCommand("add second note");
await noteCommand("clear");
expect(uiArgs("confirm").at(-1)).toEqual([
"Clear notes?",
"Remove 2 pending notes?",
]);
expect(customEntries("notes-state").at(-1)).toEqual({
op: "clear",
clearedAt: expect.any(Number),
});
expect(latestWidget()).toBeUndefined();
});
it("keeps notes when clear confirmation is rejected", async () => {
t = await createTestSession({
extensions: [extensionPath()],
mockUI: { confirm: false },
});
await noteCommand("add first note");
await noteCommand("clear");
expect(customEntries("notes-state")).toHaveLength(1);
expect(renderLatestWidget()).toEqual([
" 1 notes · alt+n expand · last: first note",
]);
});
it("edits note text and keeps old text on cancel or whitespace save", async () => {
t = await createTestSession({
extensions: [extensionPath()],
mockUI: { editor: "edited note" },
});
await noteCommand("add old note");
await noteCommand("edit 1");
expect(uiArgs("editor").at(-1)).toEqual(["Edit note 1", "old note"]);
expect(customEntries("notes-state").at(-1)).toEqual({
op: "edit",
id: 1,
text: "edited note",
updatedAt: expect.any(Number),
});
expect(renderLatestWidget()).toEqual([
" 1 notes · alt+n expand · last: edited note",
]);
t.dispose();
t = await createTestSession({
extensions: [extensionPath()],
mockUI: { editor: () => undefined },
});
await noteCommand("add stable note");
await noteCommand("edit 1");
expect(customEntries("notes-state")).toHaveLength(1);
t.dispose();
t = await createTestSession({
extensions: [extensionPath()],
mockUI: { editor: " " },
});
await noteCommand("add stable note");
await noteCommand("edit 1");
expect(customEntries("notes-state")).toHaveLength(1);
expect(uiArgs("notify").at(-1)).toEqual(["Note text required", "warning"]);
});
it("unknown ids do not mutate state", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
await noteCommand("add first note");
await noteCommand("rm 99");
await noteCommand("edit 99");
expect(customEntries("notes-state")).toHaveLength(1);
expect(uiArgs("notify").at(-1)).toEqual(["Unknown note id: 99", "error"]);
});
it("sends exact note text when idle and removes it", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
const sent: Array<{ content: unknown; options: unknown }> = [];
t.session.extensionRunner.runtime.sendUserMessage = (
content: unknown,
options: unknown,
) => sent.push({ content, options });
await noteCommand("add exact text");
await noteCommand("send 1");
expect(sent).toEqual([{ content: "exact text", options: undefined }]);
expect(customEntries("notes-state").at(-1)).toEqual({
op: "remove",
id: 1,
removedAt: expect.any(Number),
});
expect(latestWidget()).toBeUndefined();
});
it("queues send as follow-up when busy", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
const sent: Array<{ content: unknown; options: unknown }> = [];
t.session.extensionRunner.runtime.sendUserMessage = (
content: unknown,
options: unknown,
) => sent.push({ content, options });
await noteCommand("add busy text");
const command =
t.session.extensionRunner.extensions[0].commands.get("note");
const ctx = t.session.extensionRunner.createCommandContext();
ctx.isIdle = () => false;
await command.handler("send 1", ctx);
expect(sent).toEqual([
{
content: "busy text",
options: { deliverAs: "followUp" },
},
]);
expect(customEntries("notes-state").at(-1)).toEqual({
op: "remove",
id: 1,
removedAt: expect.any(Number),
});
});
it("unknown send id does not send or mutate", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
const sent: Array<{ content: unknown; options: unknown }> = [];
t.session.extensionRunner.runtime.sendUserMessage = (
content: unknown,
options: unknown,
) => sent.push({ content, options });
await noteCommand("add stable text");
await noteCommand("send 99");
expect(sent).toEqual([]);
expect(customEntries("notes-state")).toHaveLength(1);
expect(uiArgs("notify").at(-1)).toEqual(["Unknown note id: 99", "error"]);
});
it("autocompletes subcommands and pending note ids with previews", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
const command =
t.session.extensionRunner.extensions[0].commands.get("note");
await noteCommand("add consider split parser tests");
await noteCommand("add ask whether command should support autocomplete");
expect(command.getArgumentCompletions("")).toEqual([
{ value: "add", label: "add" },
{ value: "send", label: "send" },
{ value: "edit", label: "edit" },
{ value: "rm", label: "rm" },
{ value: "clear", label: "clear" },
]);
expect(command.getArgumentCompletions("send ")).toEqual([
{ value: "send 1", label: "1 consider split parser tests" },
{
value: "send 2",
label: "2 ask whether command should support autocomplete",
},
]);
expect(command.getArgumentCompletions("edit 2")).toEqual([
{
value: "edit 2",
label: "2 ask whether command should support autocomplete",
},
]);
expect(command.getArgumentCompletions("rm ")).toEqual([
{ value: "rm 1", label: "1 consider split parser tests" },
{
value: "rm 2",
label: "2 ask whether command should support autocomplete",
},
]);
});
it("replay uses only entries returned by the current branch", () => {
const state = __test.replayNotes([
{
type: "custom",
customType: "notes-state",
data: { op: "add", id: 2, text: "current branch", createdAt: 1 },
},
]);
expect(__test.pendingNotes(state)).toEqual([
{
id: 2,
text: "current branch",
},
]);
expect(state.nextId).toBe(3);
});
it("replays add, edit, remove, and clear events in order", () => {
const state = __test.replayNotes([
{
type: "custom",
customType: "notes-state",
data: { op: "add", id: 1, text: "one", createdAt: 1 },
},
{
type: "custom",
customType: "notes-state",
data: { op: "add", id: 2, text: "two", createdAt: 2 },
},
{
type: "custom",
customType: "notes-state",
data: { op: "edit", id: 2, text: "two edited", updatedAt: 3 },
},
{
type: "custom",
customType: "notes-state",
data: { op: "remove", id: 1, removedAt: 4 },
},
{
type: "custom",
customType: "notes-state",
data: { op: "clear", clearedAt: 5 },
},
{
type: "custom",
customType: "notes-state",
data: { op: "add", id: 3, text: "three", createdAt: 6 },
},
]);
expect(__test.pendingNotes(state)).toEqual([{ id: 3, text: "three" }]);
expect(state.nextId).toBe(4);
});
it("ignores malformed entries and invalid edits or removes", () => {
const state = __test.replayNotes([
{
type: "custom",
customType: "notes-state",
data: { op: "edit", id: 9, text: "missing", updatedAt: 1 },
},
{
type: "custom",
customType: "notes-state",
data: { op: "remove", id: 9, removedAt: 2 },
},
{
type: "custom",
customType: "other",
data: { op: "add", id: 1, text: "wrong", createdAt: 3 },
},
{
type: "custom",
customType: "notes-state",
data: { op: "add", id: 2, text: "ok", createdAt: 4 },
},
{
type: "custom",
customType: "notes-state",
data: { op: "add", id: "bad", text: "bad", createdAt: 5 },
},
]);
expect(__test.pendingNotes(state)).toEqual([{ id: 2, text: "ok" }]);
expect(state.nextId).toBe(3);
});
it("appends notes-state entries through commands", async () => {
t = await createTestSession({ extensions: [extensionPath()] });
const command =
t.session.extensionRunner.extensions[0].commands.get("note");
await command.handler(
"add remember parser tests",
t.session.extensionRunner.createCommandContext(),
);
expect(customEntries("notes-state")).toEqual([
{
op: "add",
id: 1,
text: "remember parser tests",
createdAt: expect.any(Number),
},
]);
});
});