repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(notes): launch sessions from pending notes

4681cba5f3d386f154a51c1e31063a50e6676940

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (4)

+833 / −18 text lines

Diff layout

extensions/notes/README.md

Modified

+18 / −2 text lines

1414- `/note` — toggle the notes widget between compact and expanded mode.
1515- `/note add <text>` — park a non-empty note.
1616- `/note send <id>`: send one note with Pi prompt expansion and remove it from pending notes.
17- `/note clone <id>`: clone the current branch through its leaf and send the note as the next prompt.
18- `/note fork <id>`: choose a user message with Pi's fork selector, fork before it, and send the note instead.
19- `/note new <id>`: start an independent session and send the note as its first prompt.
1720- `/note edit <id>` — edit one pending note.
1821- `/note rm <id>` — remove one pending note.
1922- `/note clear` — confirm and remove all pending notes.
3134## Behavior
3336Store `/template args` with `/note add /template args`; `/note send <id>` expands it at send time.
34Plain text is unchanged; busy agents receive prompts as follow-ups.
35Pi also expands skill commands and dispatches extension commands, which run immediately even when busy.
37Plain text is unchanged; busy agents receive `/note send` prompts as follow-ups.
38Pi also expands skill commands and dispatches extension commands.
40`clone`, `fork`, and `new` require an idle agent, then start the submitted note immediately in the destination session.
41A persisted source must already be saved, so wait for the first assistant response before using them in a newly created session.
42In-memory sessions are supported, but have no independently resumable source to retain.
43`clone` preserves the current branch through its leaf.
44`fork` reuses Pi's user-message selector and replaces the selected prompt and its following branch with the note.
45`new` creates a root session without a parent or the ordinary notes carry prompt.
46Cancelling or vetoing a transition keeps the source note pending.
47The destination stages the note before delivery and source consumption.
48A delivery failure leaves the destination note pending and leaves any persisted source copy untouched; successful Pi input processing consumes both.
49A crash between those operations can duplicate the note but cannot silently destroy the source copy.
50Delivery means Pi processed the input normally, not that a model response or invoked extension command succeeded.
51Other notes follow normal branch history: clone inherits current notes, fork inherits notes at the selected point, and new inherits none.
3753Pending notes are persisted as `notes-state` custom session entries.
3854Custom entries are invisible to the model context.

extensions/notes/__tests__/harness.test.ts

Modified

+393 / −2 text lines

1import { join } from "node:path";
12import { fileURLToPath } from "node:url";
3import { initTheme, SessionManager } from "@earendil-works/pi-coding-agent";
24import { Text } from "@earendil-works/pi-tui";
35import { afterEach, describe, expect, it, vi } from "vitest";
46import {
6971afterEach(() => {
7072 vi.restoreAllMocks();
73 __test.clearLaunch();
7174 __test.takeNewSessionNotes();
7275 t?.dispose();
7376 t = undefined;
166169 expect(customEntries("notes-state").at(-1)).toEqual({
167170 op: "add",
168171 id: 8,
172 key: expect.any(String),
169173 text: "next note",
170174 createdAt: expect.any(Number),
171175 });
195199 {
196200 op: "add",
197201 id: 1,
202 key: expect.any(String),
198203 text: "carried note",
199204 createdAt: expect.any(Number),
200205 },
430435 expect(uiArgs("notify").at(-1)).toEqual(["Unknown note id: 99", "error"]);
431436 });
438 it("clones through the current leaf and consumes the persisted source note", async () => {
439 t = await createTestSession({ extensions: [extensionPath()] });
440 await noteCommand("add launch this");
441 await noteCommand("add leave this pending");
442 const runner = t.session.extensionRunner;
443 const source = SessionManager.create(t.cwd, join(t.cwd, "sessions"));
444 source.appendMessage({
445 role: "user",
446 content: "source prompt",
447 timestamp: Date.now(),
448 });
449 source.appendMessage({
450 role: "assistant",
451 content: [{ type: "text", text: "source response" }],
452 timestamp: Date.now(),
453 } as never);
454 for (const entry of customEntries("notes-state")) {
455 source.appendCustomEntry("notes-state", entry);
456 }
457 const sourceFile = source.getSessionFile();
458 const sourceLeafId = source.getLeafId();
459 expect(sourceFile).toBeDefined();
460 const command = runner.extensions[0].commands.get("note");
461 const ctx = runner.createCommandContext() as any;
462 const sourceView = Object.create(ctx.sessionManager);
463 sourceView.getSessionFile = () => sourceFile;
464 sourceView.getSessionId = () => source.getSessionId();
465 sourceView.getLeafId = () => sourceLeafId;
466 Object.defineProperty(ctx, "sessionManager", { value: sourceView });
467 const sent: Array<{ content: unknown; options: unknown }> = [];
468 ctx.fork = vi.fn(async (entryId, options) => {
469 expect(entryId).toBe(sourceLeafId);
470 expect(options.position).toBe("at");
471 await runner.emit({
472 type: "session_shutdown",
473 reason: "fork",
474 targetSessionFile: undefined,
475 });
476 await runner.emit({
477 type: "session_start",
478 reason: "fork",
479 previousSessionFile: sourceFile,
480 });
481 await options.withSession({
482 ...ctx,
483 sendUserMessage: async (content: unknown, sendOptions: unknown) => {
484 sent.push({ content, options: sendOptions });
485 },
486 });
487 return { cancelled: false };
488 });
490 await command.handler("clone 1", ctx);
492 expect(sent).toEqual([
493 {
494 content: "launch this",
495 options: { expandPromptTemplates: true },
496 },
497 ]);
498 expect(renderLatestWidget()).toEqual([
499 "󰎚 1 notes · alt+n expand · last: leave this pending",
500 ]);
501 expect(uiArgs("setEditorText").at(-1)).toEqual([""]);
502 const sourceState = __test.replayNotes(
503 SessionManager.open(sourceFile ?? "").getBranch() as any,
504 );
505 expect(__test.pendingNotes(sourceState).map((note) => note.text)).toEqual([
506 "leave this pending",
507 ]);
508 });
510 it("forks before the message chosen with Pi's selector", async () => {
511 t = await createTestSession({ extensions: [extensionPath()] });
512 initTheme("dark", false);
513 const runner = t.session.extensionRunner;
514 const manager = t.session.sessionManager as any;
515 const messageId = manager.appendMessage({
516 role: "user",
517 content: [{ type: "text", text: "replace this prompt" }],
518 timestamp: Date.now(),
519 });
520 await runner.emit({
521 type: "session_tree",
522 oldLeafId: "old",
523 newLeafId: messageId,
524 });
525 await noteCommand("add replacement note");
526 const command = runner.extensions[0].commands.get("note");
527 const ctx = runner.createCommandContext() as any;
528 Object.defineProperty(ctx, "mode", { configurable: true, value: "tui" });
529 ctx.ui.custom = vi.fn(async (factory) => {
530 const component = factory({ requestRender() {} }, {}, {}, () => {});
531 expect(component.render(80).join("\n")).toContain("replace this prompt");
532 return messageId;
533 });
534 const sent: string[] = [];
535 ctx.fork = vi.fn(async (entryId, options) => {
536 expect(entryId).toBe(messageId);
537 expect(options.position).toBe("before");
538 await runner.emit({
539 type: "session_shutdown",
540 reason: "fork",
541 targetSessionFile: undefined,
542 });
543 manager.resetLeaf();
544 await runner.emit({
545 type: "session_start",
546 reason: "fork",
547 previousSessionFile: undefined,
548 });
549 await options.withSession({
550 ...ctx,
551 sendUserMessage: async (content: string) => sent.push(content),
552 });
553 return { cancelled: false };
554 });
556 await command.handler("fork 1", ctx);
558 expect(ctx.ui.custom).toHaveBeenCalledOnce();
559 expect(sent).toEqual(["replacement note"]);
560 expect(latestWidget()).toBeUndefined();
561 });
563 it("starts an independent fresh extension session without carrying other notes", async () => {
564 t = await createTestSession({ extensions: [extensionPath()] });
565 const destination = await createTestSession({
566 extensions: [extensionPath()],
567 });
568 try {
569 await noteCommand("add launch this");
570 await noteCommand("add do not carry this");
571 const sourceRunner = t.session.extensionRunner;
572 const destinationRunner = destination.session.extensionRunner;
573 const destinationManager = destination.session.sessionManager as any;
574 const command = sourceRunner.extensions[0].commands.get("note");
575 const sourceCtx = sourceRunner.createCommandContext() as any;
576 const sent: string[] = [];
577 sourceCtx.newSession = vi.fn(async (options) => {
578 expect(options.parentSession).toBeUndefined();
579 await sourceRunner.emit({
580 type: "session_shutdown",
581 reason: "new",
582 targetSessionFile: undefined,
583 });
584 await destinationRunner.emit({
585 type: "session_start",
586 reason: "new",
587 previousSessionFile: undefined,
588 });
589 await options.withSession({
590 ...(destinationRunner.createCommandContext() as any),
591 sendUserMessage: async (content: string) => sent.push(content),
592 });
593 return { cancelled: false };
594 });
596 await command.handler("new 1", sourceCtx);
598 expect(sent).toEqual(["launch this"]);
599 expect(destination.events.uiCallsFor("confirm")).toEqual([]);
600 expect(
601 destination.events
602 .uiCallsFor("setWidget")
603 .filter((call) => call.args[0] === "notes")
604 .at(-1)?.args[1],
605 ).toBeUndefined();
606 expect(destinationManager.getHeader().parentSession).toBeUndefined();
607 } finally {
608 destination.dispose();
609 }
610 });
612 it("keeps the note in the destination when delivery fails", async () => {
613 t = await createTestSession({ extensions: [extensionPath()] });
614 await noteCommand("add recover me");
615 const runner = t.session.extensionRunner;
616 const manager = t.session.sessionManager as any;
617 const command = runner.extensions[0].commands.get("note");
618 const ctx = runner.createCommandContext() as any;
619 ctx.newSession = vi.fn(async (options) => {
620 await runner.emit({
621 type: "session_shutdown",
622 reason: "new",
623 targetSessionFile: undefined,
624 });
625 manager.newSession();
626 await runner.emit({
627 type: "session_start",
628 reason: "new",
629 previousSessionFile: undefined,
630 });
631 await options.withSession({
632 ...ctx,
633 sendUserMessage: async () => {
634 throw new Error("dispatch failed");
635 },
636 });
637 return { cancelled: false };
638 });
640 await command.handler("new 1", ctx);
642 expect(renderLatestWidget()).toEqual([
643 "󰎚 1 notes · alt+n expand · last: recover me",
644 ]);
645 expect(uiArgs("notify").at(-1)).toEqual([
646 "Note remains pending: dispatch failed",
647 "error",
648 ]);
649 });
651 it("reserves the destination note while delivery is pending", async () => {
652 t = await createTestSession({ extensions: [extensionPath()] });
653 await noteCommand("add in flight");
654 const runner = t.session.extensionRunner;
655 const manager = t.session.sessionManager as any;
656 const command = runner.extensions[0].commands.get("note");
657 const ctx = runner.createCommandContext() as any;
658 let finishDelivery: (() => void) | undefined;
659 ctx.newSession = vi.fn(async (options) => {
660 await runner.emit({
661 type: "session_shutdown",
662 reason: "new",
663 targetSessionFile: undefined,
664 });
665 manager.newSession();
666 await runner.emit({
667 type: "session_start",
668 reason: "new",
669 previousSessionFile: undefined,
670 });
671 await options.withSession({
672 ...ctx,
673 sendUserMessage: () =>
674 new Promise<void>((resolve) => {
675 finishDelivery = resolve;
676 }),
677 });
678 return { cancelled: false };
679 });
681 const delivery = command.handler("new 1", ctx);
682 await expect.poll(() => finishDelivery).toBeTypeOf("function");
683 await command.handler("edit 1", runner.createCommandContext());
685 expect(uiArgs("editor")).toEqual([]);
686 expect(uiArgs("notify").at(-1)).toEqual([
687 "Note 1 is being delivered",
688 "warning",
689 ]);
690 finishDelivery?.();
691 await delivery;
692 expect(latestWidget()).toBeUndefined();
693 });
695 it("claims the destination once across a nested in-memory switch", async () => {
696 t = await createTestSession({
697 extensions: [extensionPath()],
698 mockUI: { confirm: true },
699 });
700 await noteCommand("add switch again");
701 const runner = t.session.extensionRunner;
702 const manager = t.session.sessionManager as any;
703 const command = runner.extensions[0].commands.get("note");
704 const ctx = runner.createCommandContext() as any;
705 ctx.newSession = vi.fn(async (options) => {
706 await runner.emit({
707 type: "session_shutdown",
708 reason: "new",
709 targetSessionFile: undefined,
710 });
711 manager.newSession();
712 await runner.emit({
713 type: "session_start",
714 reason: "new",
715 previousSessionFile: undefined,
716 });
717 await options.withSession({
718 ...ctx,
719 sendUserMessage: async () => {
720 await command.handler(
721 "add nested note",
722 runner.createCommandContext(),
723 );
724 await runner.emit({
725 type: "session_shutdown",
726 reason: "new",
727 targetSessionFile: undefined,
728 });
729 manager.newSession();
730 await runner.emit({
731 type: "session_start",
732 reason: "new",
733 previousSessionFile: undefined,
734 });
735 },
736 });
737 return { cancelled: false };
738 });
740 await expect(command.handler("new 1", ctx)).resolves.toBeUndefined();
741 expect(uiArgs("confirm").at(-1)).toEqual([
742 "Carry notes?",
743 "Copy 2 pending notes into the new session?",
744 ]);
745 expect(renderLatestWidget()).toEqual([
746 "󰎚 2 notes · alt+n expand · last: nested note",
747 ]);
749 await command.handler("rm 1", runner.createCommandContext());
750 expect(renderLatestWidget()).toEqual([
751 "󰎚 1 notes · alt+n expand · last: nested note",
752 ]);
753 });
755 it("keeps the source note when a transition is cancelled or busy", async () => {
756 t = await createTestSession({ extensions: [extensionPath()] });
757 await noteCommand("add stable note");
758 const runner = t.session.extensionRunner;
759 const command = runner.extensions[0].commands.get("note");
760 const cancelled = runner.createCommandContext() as any;
761 cancelled.newSession = vi.fn(async () => ({ cancelled: true }));
762 await command.handler("new 1", cancelled);
764 const busy = runner.createCommandContext() as any;
765 busy.isIdle = () => false;
766 busy.newSession = vi.fn();
767 await command.handler("new 1", busy);
769 expect(renderLatestWidget()).toEqual([
770 "󰎚 1 notes · alt+n expand · last: stable note",
771 ]);
772 expect(busy.newSession).not.toHaveBeenCalled();
773 expect(uiArgs("notify").at(-1)).toEqual([
774 "Cannot new while the agent is busy",
775 "warning",
776 ]);
777 });
779 it("rejects a persisted source that has not been saved yet", async () => {
780 t = await createTestSession({ extensions: [extensionPath()] });
781 await noteCommand("add stable note");
782 const runner = t.session.extensionRunner;
783 const command = runner.extensions[0].commands.get("note");
784 const base = runner.createCommandContext() as any;
785 const sessionManager = Object.create(base.sessionManager);
786 sessionManager.getSessionFile = () => join(t.cwd, "not-created.jsonl");
787 const ctx = Object.create(base);
788 Object.defineProperty(ctx, "sessionManager", { value: sessionManager });
789 ctx.newSession = vi.fn();
791 await command.handler("new 1", ctx);
793 expect(ctx.newSession).not.toHaveBeenCalled();
794 expect(uiArgs("notify").at(-1)).toEqual([
795 "Current session is not saved yet; wait for the first assistant response",
796 "warning",
797 ]);
798 expect(renderLatestWidget()).toEqual([
799 "󰎚 1 notes · alt+n expand · last: stable note",
800 ]);
801 });
433803 it("autocompletes subcommands and pending note ids with previews", async () => {
434804 t = await createTestSession({ extensions: [extensionPath()] });
435805 const command =
440810 expect(command.getArgumentCompletions("")).toEqual([
441811 { value: "add", label: "add" },
442812 { value: "send", label: "send" },
813 { value: "clone", label: "clone" },
814 { value: "fork", label: "fork" },
815 { value: "new", label: "new" },
443816 { value: "edit", label: "edit" },
444817 { value: "rm", label: "rm" },
445818 { value: "clear", label: "clear" },
451824 label: "2 ask whether command should support autocomplete",
452825 },
453826 ]);
827 expect(command.getArgumentCompletions("clone 1")).toEqual([
828 { value: "clone 1", label: "1 consider split parser tests" },
829 ]);
830 expect(command.getArgumentCompletions("fork 2")).toEqual([
831 {
832 value: "fork 2",
833 label: "2 ask whether command should support autocomplete",
834 },
835 ]);
836 expect(command.getArgumentCompletions("new 1")).toEqual([
837 { value: "new 1", label: "1 consider split parser tests" },
838 ]);
454839 expect(command.getArgumentCompletions("edit 2")).toEqual([
455840 {
456841 value: "edit 2",
478863 expect(__test.pendingNotes(state)).toEqual([
479864 {
480865 id: 2,
866 key: "legacy:2:1",
481867 text: "current branch",
482868 },
483869 ]);
518904 },
519905 ]);
521 expect(__test.pendingNotes(state)).toEqual([{ id: 3, text: "three" }]);
907 expect(__test.pendingNotes(state)).toEqual([
908 { id: 3, key: "legacy:3:6", text: "three" },
909 ]);
522910 expect(state.nextId).toBe(4);
523911 });
551939 },
552940 ]);
554 expect(__test.pendingNotes(state)).toEqual([{ id: 2, text: "ok" }]);
942 expect(__test.pendingNotes(state)).toEqual([
943 { id: 2, key: "legacy:2:4", text: "ok" },
944 ]);
555945 expect(state.nextId).toBe(3);
556946 });
568958 {
569959 op: "add",
570960 id: 1,
961 key: expect.any(String),
571962 text: "remember parser tests",
572963 createdAt: expect.any(Number),
573964 },

extensions/notes/index.ts

Modified

+413 / −14 text lines

1import type {
2 ExtensionAPI,
3 ExtensionContext,
1import { existsSync } from "node:fs";
2import {
3 type ExtensionAPI,
4 type ExtensionCommandContext,
5 type ExtensionContext,
6 SessionManager,
7 UserMessageSelectorComponent,
48} from "@earendil-works/pi-coding-agent";
59import type { AutocompleteItem } from "@earendil-works/pi-tui";
610import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
1014const NOTES_ICON = "󰎚";
1115const WIDGET_DEFAULT_WIDTH = 80;
1216const NEW_SESSION_NOTES = Symbol.for("@bugabinga/pi-ext-notes/new-session");
17const NOTE_LAUNCH = Symbol.for("@bugabinga/pi-ext-notes/launch");
14type Note = { id: number; text: string };
19type Note = { id: number; key: string; text: string };
1520type NotesEvent =
16 | { op: "add"; id: number; text: string; createdAt: number }
21 | { op: "add"; id: number; key?: string; text: string; createdAt: number }
1722 | { op: "edit"; id: number; text: string; updatedAt: number }
1823 | { op: "remove"; id: number; removedAt: number }
1924 | { op: "clear"; clearedAt: number };
2126type SessionEntryLike = {
27 id?: unknown;
2228 type?: unknown;
2329 customType?: unknown;
2430 data?: unknown;
31 message?: unknown;
2532};
2734type NotesState = {
2936 nextId: number;
3037};
39type NoteLaunchKind = "clone" | "fork" | "new";
41type DestinationReceiver = {
42 instanceToken: string;
43 consume(): boolean;
44 fail(message: string): void;
45 revoke(): void;
46};
48type ReplacementContext = ExtensionCommandContext & {
49 sendUserMessage(
50 content: string,
51 options?: { expandPromptTemplates?: boolean },
52 ): Promise<void>;
53};
55type NoteLaunch = {
56 token: string;
57 sourceInstanceToken: string;
58 sourceSessionId: string;
59 kind: NoteLaunchKind;
60 note: Note;
61 sourceLeafId?: string;
62 sourceSessionFile?: string;
63 targetSessionFile?: string;
64 shutdownSeen: boolean;
65 destinationClaimed: boolean;
66 replacementContext?: ReplacementContext;
67 receiver?: DestinationReceiver;
68};
3270function createState(): NotesState {
3371 return { notes: new Map(), nextId: 1 };
5391 return {
5492 op: "add",
5593 id: event.id,
94 key: isNonEmptyText(event.key) ? event.key.trim() : undefined,
5695 text: event.text.trim(),
5796 createdAt: event.createdAt,
5897 };
86125function applyEvent(state: NotesState, event: NotesEvent): void {
87126 if (event.op === "add") {
88 state.notes.set(event.id, { id: event.id, text: event.text });
127 state.notes.set(event.id, {
128 id: event.id,
129 key: event.key ?? `legacy:${event.id}:${event.createdAt}`,
130 text: event.text,
131 });
89132 state.nextId = Math.max(state.nextId, event.id + 1);
90133 return;
91134 }
92135 if (event.op === "edit") {
93136 const note = state.notes.get(event.id);
94137 if (!note) return;
95 state.notes.set(event.id, { id: event.id, text: event.text });
138 state.notes.set(event.id, { ...note, text: event.text });
96139 state.nextId = Math.max(state.nextId, event.id + 1);
97140 return;
98141 }
119162 return [...state.notes.values()].sort((a, b) => a.id - b.id);
165function noteWithKey(state: NotesState, key: string): Note | undefined {
166 return pendingNotes(state).find((note) => note.key === key);
167}
122169function replaceState(target: NotesState, source: NotesState): void {
123170 target.notes = source.notes;
124171 target.nextId = source.nextId;
148195 return notes;
198function activeLaunch(): NoteLaunch | undefined {
199 const launch = Reflect.get(globalThis, NOTE_LAUNCH);
200 return launch && typeof launch === "object"
201 ? (launch as NoteLaunch)
202 : undefined;
203}
205function startLaunch(launch: NoteLaunch): boolean {
206 if (activeLaunch()) return false;
207 Reflect.set(globalThis, NOTE_LAUNCH, launch);
208 return true;
209}
211function finishLaunch(launch: NoteLaunch): void {
212 if (activeLaunch()?.token === launch.token) {
213 Reflect.deleteProperty(globalThis, NOTE_LAUNCH);
214 }
215}
217function launchReason(kind: NoteLaunchKind): "fork" | "new" {
218 return kind === "new" ? "new" : "fork";
219}
151221function appendEvent(
152222 pi: ExtensionAPI,
153223 state: NotesState,
299369 return state.notes.get(id);
302const SUBCOMMANDS = ["add", "send", "edit", "rm", "clear"] as const;
372function messageText(content: unknown): string {
373 if (typeof content === "string") return content;
374 if (!Array.isArray(content)) return "";
375 return content
376 .filter(
377 (part): part is { type: "text"; text: string } =>
378 part !== null &&
379 typeof part === "object" &&
380 Reflect.get(part, "type") === "text" &&
381 typeof Reflect.get(part, "text") === "string",
382 )
383 .map((part) => part.text)
384 .join("");
385}
387function userMessagesForForking(
388 entries: SessionEntryLike[],
389): Array<{ entryId: string; text: string }> {
390 const messages: Array<{ entryId: string; text: string }> = [];
391 for (const entry of entries) {
392 if (entry.type !== "message" || typeof entry.id !== "string") continue;
393 if (!entry.message || typeof entry.message !== "object") continue;
394 if (Reflect.get(entry.message, "role") !== "user") continue;
395 const text = messageText(Reflect.get(entry.message, "content"));
396 if (text) messages.push({ entryId: entry.id, text });
397 }
398 return messages;
399}
401async function selectForkEntry(
402 ctx: ExtensionCommandContext,
403): Promise<string | undefined> {
404 if (ctx.mode !== "tui") {
405 notify(ctx, "Note fork requires Pi's interactive TUI", "warning");
406 return undefined;
407 }
408 const messages = userMessagesForForking(
409 ctx.sessionManager.getEntries() as SessionEntryLike[],
410 );
411 if (messages.length === 0) {
412 notify(ctx, "No messages to fork from", "info");
413 return undefined;
414 }
415 const initialSelectedId = messages.at(-1)?.entryId;
416 return ctx.ui.custom<string | undefined>(
417 (tui, _theme, _keybindings, done) => {
418 const selector = new UserMessageSelectorComponent(
419 messages.map(({ entryId, text }) => ({ id: entryId, text })),
420 done,
421 () => done(undefined),
422 initialSelectedId,
423 );
424 const list = selector.getMessageList();
425 return {
426 invalidate: () => selector.invalidate(),
427 render: (width: number) => selector.render(width),
428 handleInput(keyData: string) {
429 list.handleInput(keyData);
430 tui.requestRender();
431 },
432 };
433 },
434 );
435}
437function consumeSourceNote(launch: NoteLaunch): void {
438 const { sourceSessionFile, sourceLeafId } = launch;
439 if (!sourceSessionFile || !existsSync(sourceSessionFile)) return;
441 const manager = SessionManager.open(sourceSessionFile);
442 if (manager.getSessionId() !== launch.sourceSessionId) {
443 throw new Error("Source session identity changed before note consumption");
444 }
445 if (sourceLeafId) manager.branch(sourceLeafId);
446 else manager.resetLeaf();
447 const sourceState = replayNotes(manager.getBranch() as SessionEntryLike[]);
448 const note = noteWithKey(sourceState, launch.note.key);
449 if (!note) {
450 throw new Error("Source note changed before it could be consumed");
451 }
452 manager.appendCustomEntry(ENTRY_TYPE, {
453 op: "remove",
454 id: note.id,
455 removedAt: Date.now(),
456 } satisfies NotesEvent);
457}
459function errorMessage(error: unknown): string {
460 return error instanceof Error ? error.message : String(error);
461}
463const SUBCOMMANDS = [
464 "add",
465 "send",
466 "clone",
467 "fork",
468 "new",
469 "edit",
470 "rm",
471 "clear",
472] as const;
304474function argumentCompletions(
305475 state: NotesState,
314484 }),
315485 );
316486 }
317 if (command !== "send" && command !== "edit" && command !== "rm") return [];
487 if (
488 command !== "send" &&
489 command !== "clone" &&
490 command !== "fork" &&
491 command !== "new" &&
492 command !== "edit" &&
493 command !== "rm"
494 )
495 return [];
318496 return pendingNotes(state)
319497 .filter((note) => String(note.id).startsWith(rest))
320498 .map((note) => ({
326504export default function notesExtension(pi: ExtensionAPI): void {
505 const instanceToken = crypto.randomUUID();
506 const reservedNoteKeys = new Set<string>();
327507 const state = createState();
328508 let expanded = false;
351531 refreshWidget(ctx);
352532 }
534 function rejectReservedNote(ctx: ExtensionContext, note: Note): boolean {
535 if (!reservedNoteKeys.has(note.key)) return false;
536 notify(ctx, `Note ${note.id} is being delivered`, "warning");
537 return true;
538 }
540 function stageLaunch(ctx: ExtensionContext, launch: NoteLaunch): void {
541 let staged = noteWithKey(state, launch.note.key);
542 if (!staged) {
543 appendEvent(pi, state, {
544 op: "add",
545 id: state.nextId,
546 key: launch.note.key,
547 text: launch.note.text,
548 createdAt: Date.now(),
549 });
550 staged = noteWithKey(state, launch.note.key);
551 } else if (staged.text !== launch.note.text) {
552 appendEvent(pi, state, {
553 op: "edit",
554 id: staged.id,
555 text: launch.note.text,
556 updatedAt: Date.now(),
557 });
558 staged = noteWithKey(state, launch.note.key);
559 }
560 if (!staged) throw new Error("Failed to stage note in destination session");
561 reservedNoteKeys.add(launch.note.key);
562 refreshWidget(ctx);
564 let active = true;
565 launch.receiver = {
566 instanceToken,
567 consume() {
568 if (!active) return false;
569 const note = noteWithKey(state, launch.note.key);
570 if (!note) {
571 reservedNoteKeys.delete(launch.note.key);
572 return false;
573 }
574 appendEvent(pi, state, {
575 op: "remove",
576 id: note.id,
577 removedAt: Date.now(),
578 });
579 reservedNoteKeys.delete(launch.note.key);
580 refreshWidget(ctx);
581 return true;
582 },
583 fail(message) {
584 if (!active) return;
585 reservedNoteKeys.delete(launch.note.key);
586 notify(ctx, `Note remains pending: ${message}`, "error");
587 refreshWidget(ctx);
588 },
589 revoke() {
590 active = false;
591 reservedNoteKeys.delete(launch.note.key);
592 },
593 };
594 }
596 async function launchNote(
597 kind: NoteLaunchKind,
598 note: Note,
599 ctx: ExtensionCommandContext,
600 ): Promise<void> {
601 if (!ctx.isIdle() || ctx.hasPendingMessages()) {
602 notify(ctx, `Cannot ${kind} while the agent is busy`, "warning");
603 return;
604 }
605 if (activeLaunch()) {
606 notify(ctx, "Another note session transition is active", "warning");
607 return;
608 }
609 const sourceSessionFile = ctx.sessionManager.getSessionFile() ?? undefined;
610 if (sourceSessionFile && !existsSync(sourceSessionFile)) {
611 notify(
612 ctx,
613 "Current session is not saved yet; wait for the first assistant response",
614 "warning",
615 );
616 return;
617 }
619 let targetEntryId: string | undefined;
620 if (kind === "fork") {
621 targetEntryId = await selectForkEntry(ctx);
622 if (!targetEntryId) return;
623 if (!ctx.isIdle() || ctx.hasPendingMessages()) {
624 notify(ctx, "Cannot fork while the agent is busy", "warning");
625 return;
626 }
627 const currentNote = state.notes.get(note.id);
628 if (currentNote?.key !== note.key || currentNote.text !== note.text) {
629 notify(
630 ctx,
631 `Note ${note.id} changed while selecting a fork`,
632 "warning",
633 );
634 return;
635 }
636 }
638 const sourceLeafId = ctx.sessionManager.getLeafId() ?? undefined;
639 if (kind === "clone" && !sourceLeafId) {
640 notify(ctx, "Nothing to clone yet", "info");
641 return;
642 }
643 const launch: NoteLaunch = {
644 token: crypto.randomUUID(),
645 sourceInstanceToken: instanceToken,
646 sourceSessionId: ctx.sessionManager.getSessionId(),
647 kind,
648 note: structuredClone(note),
649 sourceLeafId,
650 sourceSessionFile,
651 shutdownSeen: false,
652 destinationClaimed: false,
653 };
654 if (!startLaunch(launch)) {
655 notify(ctx, "Another note session transition is active", "warning");
656 return;
657 }
659 try {
660 const withSession = async (replacement: ReplacementContext) => {
661 launch.replacementContext = replacement;
662 };
663 const result =
664 kind === "new"
665 ? await ctx.newSession({ withSession })
666 : await ctx.fork(targetEntryId ?? sourceLeafId ?? "", {
667 position: kind === "clone" ? "at" : "before",
668 withSession,
669 });
670 if (result.cancelled) return;
672 const replacement = launch.replacementContext;
673 const receiver = launch.receiver;
674 if (!replacement || !receiver) {
675 replacement?.ui.notify(
676 "Note session transition completed without a destination handoff",
677 "error",
678 );
679 return;
680 }
681 replacement.ui.setEditorText("");
682 try {
683 await replacement.sendUserMessage(launch.note.text, {
684 expandPromptTemplates: true,
685 });
686 } catch (error) {
687 receiver.fail(errorMessage(error));
688 return;
689 }
690 try {
691 if (!receiver.consume()) return;
692 } catch (error) {
693 receiver.fail(errorMessage(error));
694 return;
695 }
696 try {
697 consumeSourceNote(launch);
698 } catch (error) {
699 replacement.ui.notify(
700 `Note delivered; source copy remains pending: ${errorMessage(error)}`,
701 "warning",
702 );
703 }
704 } finally {
705 finishLaunch(launch);
706 }
707 }
354709 pi.registerCommand("note", {
355 description: "Park, inspect, edit, send, or clear pending prompt notes.",
710 description: "Park, edit, send, or launch sessions from prompt notes.",
356711 getArgumentCompletions: (argumentPrefix) =>
357712 argumentCompletions(state, argumentPrefix),
358713 async handler(args, ctx) {
374729 appendEvent(pi, state, {
375730 op: "add",
376731 id: state.nextId,
732 key: crypto.randomUUID(),
377733 text,
378734 createdAt: Date.now(),
379735 });
385741 if (command === "rm") {
386742 const note = requireNote(ctx, state, rest);
387 if (!note) return;
743 if (!note || rejectReservedNote(ctx, note)) return;
388744 appendEvent(pi, state, {
389745 op: "remove",
390746 id: note.id,
395751 }
397753 if (command === "clear") {
754 if (reservedNoteKeys.size > 0) {
755 notify(ctx, "A note is being delivered", "warning");
756 return;
757 }
398758 if (state.notes.size === 0) {
399759 notify(ctx, "No pending notes", "info");
400760 refreshWidget(ctx);
413773 if (command === "edit") {
414774 const note = requireNote(ctx, state, rest);
415 if (!note) return;
775 if (!note || rejectReservedNote(ctx, note)) return;
416776 const edited = await ctx.ui.editor(`Edit note ${note.id}`, note.text);
417777 if (edited === undefined) return;
418778 const text = edited.trim();
433793 if (command === "send") {
434794 const note = requireNote(ctx, state, rest);
435 if (!note) return;
795 if (!note || rejectReservedNote(ctx, note)) return;
436796 pi.sendUserMessage(note.text, {
437797 expandPromptTemplates: true,
438798 deliverAs: ctx.isIdle() ? undefined : "followUp",
446806 return;
447807 }
449 notify(ctx, "Usage: /note [add|send|edit|rm|clear]", "warning");
809 if (command === "clone" || command === "fork" || command === "new") {
810 const note = requireNote(ctx, state, rest);
811 if (!note || rejectReservedNote(ctx, note)) return;
812 await launchNote(command, note, ctx);
813 return;
814 }
816 notify(
817 ctx,
818 "Usage: /note [add|send|clone|fork|new|edit|rm|clear]",
819 "warning",
820 );
450821 refreshWidget(ctx);
451822 },
452823 });
466837 }
468839 pi.on("session_shutdown", (event) => {
840 const launch = activeLaunch();
841 if (launch?.receiver?.instanceToken === instanceToken) {
842 launch.receiver.revoke();
843 }
844 if (
845 launch?.sourceInstanceToken === instanceToken &&
846 !launch.shutdownSeen &&
847 event.reason === launchReason(launch.kind)
848 ) {
849 launch.shutdownSeen = true;
850 launch.targetSessionFile = event.targetSessionFile;
851 return;
852 }
469853 if (event.reason === "new") {
470854 stashNewSessionNotes(event.targetSessionFile, pendingNotes(state));
471855 }
474858 pi.on("session_start", async (event, ctx) => {
475859 restoreBranch(ctx);
860 const launch = activeLaunch();
861 if (
862 launch?.shutdownSeen &&
863 !launch.destinationClaimed &&
864 event.reason === launchReason(launch.kind) &&
865 event.previousSessionFile === launch.sourceSessionFile &&
866 ctx.sessionManager.getSessionFile() === launch.targetSessionFile
867 ) {
868 launch.destinationClaimed = true;
869 stageLaunch(ctx, launch);
870 return;
871 }
476872 if (event.reason !== "new") return;
478874 const notes = takeNewSessionNotes(ctx.sessionManager.getSessionFile());
490886 appendEvent(pi, state, {
491887 op: "add",
492888 id: note.id,
889 key: note.key,
493890 text: note.text,
494891 createdAt: Date.now(),
495892 });
503900export const __test = {
504901 ENTRY_TYPE,
902 clearLaunch: () => Reflect.deleteProperty(globalThis, NOTE_LAUNCH),
505903 argumentCompletions,
506904 compactWidgetLine,
507905 expandedWidgetLines,
510908 preview,
511909 replayNotes,
512910 takeNewSessionNotes,
911 userMessagesForForking,
513912 widgetLines,
514913};

extensions/notes/mise.toml

Modified

+9 / −0 text lines

1[tasks.fmt]
2description = "Format notes extension"
3depends = ["//:install"]
4run = [
5 "biome check --write --config-path ../.. .",
6 "rumdl fmt --config ../../.rumdl.toml .",
7 "taplo format --config ../../.taplo.toml mise.toml",
8]
9
110[tasks.lint]
211description = "Lint notes extension"
312depends = ["//:install"]