feat(notes): launch sessions from pending notes
4681cba5f3d386f154a51c1e31063a50e6676940
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
- Parent 1: 6ec7adc2cbaf
bugabingas pi extensions
4681cba5f3d386f154a51c1e31063a50e6676940
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
+833 / −18 text lines
+18 / −2 text lines
- `/note clone <id>`: clone the current branch through its leaf and send the note as the next prompt.- `/note fork <id>`: choose a user message with Pi's fork selector, fork before it, and send the note instead.- `/note new <id>`: start an independent session and send the note as its first prompt.Store `/template args` with `/note add /template args`; `/note send <id>` expands it at send time.Plain text is unchanged; busy agents receive prompts as follow-ups.Pi also expands skill commands and dispatches extension commands, which run immediately even when busy.Plain text is unchanged; busy agents receive `/note send` prompts as follow-ups.Pi also expands skill commands and dispatches extension commands.`clone`, `fork`, and `new` require an idle agent, then start the submitted note immediately in the destination session.A persisted source must already be saved, so wait for the first assistant response before using them in a newly created session.In-memory sessions are supported, but have no independently resumable source to retain.`clone` preserves the current branch through its leaf.`fork` reuses Pi's user-message selector and replaces the selected prompt and its following branch with the note.`new` creates a root session without a parent or the ordinary notes carry prompt.Cancelling or vetoing a transition keeps the source note pending.The destination stages the note before delivery and source consumption.A delivery failure leaves the destination note pending and leaves any persisted source copy untouched; successful Pi input processing consumes both.A crash between those operations can duplicate the note but cannot silently destroy the source copy.Delivery means Pi processed the input normally, not that a model response or invoked extension command succeeded.Other notes follow normal branch history: clone inherits current notes, fork inherits notes at the selected point, and new inherits none.+393 / −2 text lines
import { join } from "node:path";import { initTheme, SessionManager } from "@earendil-works/pi-coding-agent"; __test.clearLaunch(); key: expect.any(String), key: expect.any(String), it("clones through the current leaf and consumes the persisted source note", async () => { t = await createTestSession({ extensions: [extensionPath()] }); await noteCommand("add launch this"); await noteCommand("add leave this pending"); const runner = t.session.extensionRunner; const source = SessionManager.create(t.cwd, join(t.cwd, "sessions")); source.appendMessage({ role: "user", content: "source prompt", timestamp: Date.now(), }); source.appendMessage({ role: "assistant", content: [{ type: "text", text: "source response" }], timestamp: Date.now(), } as never); for (const entry of customEntries("notes-state")) { source.appendCustomEntry("notes-state", entry); } const sourceFile = source.getSessionFile(); const sourceLeafId = source.getLeafId(); expect(sourceFile).toBeDefined(); const command = runner.extensions[0].commands.get("note"); const ctx = runner.createCommandContext() as any; const sourceView = Object.create(ctx.sessionManager); sourceView.getSessionFile = () => sourceFile; sourceView.getSessionId = () => source.getSessionId(); sourceView.getLeafId = () => sourceLeafId; Object.defineProperty(ctx, "sessionManager", { value: sourceView }); const sent: Array<{ content: unknown; options: unknown }> = []; ctx.fork = vi.fn(async (entryId, options) => { expect(entryId).toBe(sourceLeafId); expect(options.position).toBe("at"); await runner.emit({ type: "session_shutdown", reason: "fork", targetSessionFile: undefined, }); await runner.emit({ type: "session_start", reason: "fork", previousSessionFile: sourceFile, }); await options.withSession({ ...ctx, sendUserMessage: async (content: unknown, sendOptions: unknown) => { sent.push({ content, options: sendOptions }); }, }); return { cancelled: false }; }); await command.handler("clone 1", ctx); expect(sent).toEqual([ { content: "launch this", options: { expandPromptTemplates: true }, }, ]); expect(renderLatestWidget()).toEqual([ " 1 notes · alt+n expand · last: leave this pending", ]); expect(uiArgs("setEditorText").at(-1)).toEqual([""]); const sourceState = __test.replayNotes( SessionManager.open(sourceFile ?? "").getBranch() as any, ); expect(__test.pendingNotes(sourceState).map((note) => note.text)).toEqual([ "leave this pending", ]); }); it("forks before the message chosen with Pi's selector", async () => { t = await createTestSession({ extensions: [extensionPath()] }); initTheme("dark", false); const runner = t.session.extensionRunner; const manager = t.session.sessionManager as any; const messageId = manager.appendMessage({ role: "user", content: [{ type: "text", text: "replace this prompt" }], timestamp: Date.now(), }); await runner.emit({ type: "session_tree", oldLeafId: "old", newLeafId: messageId, }); await noteCommand("add replacement note"); const command = runner.extensions[0].commands.get("note"); const ctx = runner.createCommandContext() as any; Object.defineProperty(ctx, "mode", { configurable: true, value: "tui" }); ctx.ui.custom = vi.fn(async (factory) => { const component = factory({ requestRender() {} }, {}, {}, () => {}); expect(component.render(80).join("\n")).toContain("replace this prompt"); return messageId; }); const sent: string[] = []; ctx.fork = vi.fn(async (entryId, options) => { expect(entryId).toBe(messageId); expect(options.position).toBe("before"); await runner.emit({ type: "session_shutdown", reason: "fork", targetSessionFile: undefined, }); manager.resetLeaf(); await runner.emit({ type: "session_start", reason: "fork", previousSessionFile: undefined, }); await options.withSession({ ...ctx, sendUserMessage: async (content: string) => sent.push(content), }); return { cancelled: false }; }); await command.handler("fork 1", ctx); expect(ctx.ui.custom).toHaveBeenCalledOnce(); expect(sent).toEqual(["replacement note"]); expect(latestWidget()).toBeUndefined(); }); it("starts an independent fresh extension session without carrying other notes", async () => { t = await createTestSession({ extensions: [extensionPath()] }); const destination = await createTestSession({ extensions: [extensionPath()], }); try { await noteCommand("add launch this"); await noteCommand("add do not carry this"); const sourceRunner = t.session.extensionRunner; const destinationRunner = destination.session.extensionRunner; const destinationManager = destination.session.sessionManager as any; const command = sourceRunner.extensions[0].commands.get("note"); const sourceCtx = sourceRunner.createCommandContext() as any; const sent: string[] = []; sourceCtx.newSession = vi.fn(async (options) => { expect(options.parentSession).toBeUndefined(); await sourceRunner.emit({ type: "session_shutdown", reason: "new", targetSessionFile: undefined, }); await destinationRunner.emit({ type: "session_start", reason: "new", previousSessionFile: undefined, }); await options.withSession({ ...(destinationRunner.createCommandContext() as any), sendUserMessage: async (content: string) => sent.push(content), }); return { cancelled: false }; }); await command.handler("new 1", sourceCtx); expect(sent).toEqual(["launch this"]); expect(destination.events.uiCallsFor("confirm")).toEqual([]); expect( destination.events .uiCallsFor("setWidget") .filter((call) => call.args[0] === "notes") .at(-1)?.args[1], ).toBeUndefined(); expect(destinationManager.getHeader().parentSession).toBeUndefined(); } finally { destination.dispose(); } }); it("keeps the note in the destination when delivery fails", async () => { t = await createTestSession({ extensions: [extensionPath()] }); await noteCommand("add recover me"); const runner = t.session.extensionRunner; const manager = t.session.sessionManager as any; const command = runner.extensions[0].commands.get("note"); const ctx = runner.createCommandContext() as any; ctx.newSession = vi.fn(async (options) => { await runner.emit({ type: "session_shutdown", reason: "new", targetSessionFile: undefined, }); manager.newSession(); await runner.emit({ type: "session_start", reason: "new", previousSessionFile: undefined, }); await options.withSession({ ...ctx, sendUserMessage: async () => { throw new Error("dispatch failed"); }, }); return { cancelled: false }; }); await command.handler("new 1", ctx); expect(renderLatestWidget()).toEqual([ " 1 notes · alt+n expand · last: recover me", ]); expect(uiArgs("notify").at(-1)).toEqual([ "Note remains pending: dispatch failed", "error", ]); }); it("reserves the destination note while delivery is pending", async () => { t = await createTestSession({ extensions: [extensionPath()] }); await noteCommand("add in flight"); const runner = t.session.extensionRunner; const manager = t.session.sessionManager as any; const command = runner.extensions[0].commands.get("note"); const ctx = runner.createCommandContext() as any; let finishDelivery: (() => void) | undefined; ctx.newSession = vi.fn(async (options) => { await runner.emit({ type: "session_shutdown", reason: "new", targetSessionFile: undefined, }); manager.newSession(); await runner.emit({ type: "session_start", reason: "new", previousSessionFile: undefined, }); await options.withSession({ ...ctx, sendUserMessage: () => new Promise<void>((resolve) => { finishDelivery = resolve; }), }); return { cancelled: false }; }); const delivery = command.handler("new 1", ctx); await expect.poll(() => finishDelivery).toBeTypeOf("function"); await command.handler("edit 1", runner.createCommandContext()); expect(uiArgs("editor")).toEqual([]); expect(uiArgs("notify").at(-1)).toEqual([ "Note 1 is being delivered", "warning", ]); finishDelivery?.(); await delivery; expect(latestWidget()).toBeUndefined(); }); it("claims the destination once across a nested in-memory switch", async () => { t = await createTestSession({ extensions: [extensionPath()], mockUI: { confirm: true }, }); await noteCommand("add switch again"); const runner = t.session.extensionRunner; const manager = t.session.sessionManager as any; const command = runner.extensions[0].commands.get("note"); const ctx = runner.createCommandContext() as any; ctx.newSession = vi.fn(async (options) => { await runner.emit({ type: "session_shutdown", reason: "new", targetSessionFile: undefined, }); manager.newSession(); await runner.emit({ type: "session_start", reason: "new", previousSessionFile: undefined, }); await options.withSession({ ...ctx, sendUserMessage: async () => { await command.handler( "add nested note", runner.createCommandContext(), ); await runner.emit({ type: "session_shutdown", reason: "new", targetSessionFile: undefined, }); manager.newSession(); await runner.emit({ type: "session_start", reason: "new", previousSessionFile: undefined, }); }, }); return { cancelled: false }; }); await expect(command.handler("new 1", ctx)).resolves.toBeUndefined(); expect(uiArgs("confirm").at(-1)).toEqual([ "Carry notes?", "Copy 2 pending notes into the new session?", ]); expect(renderLatestWidget()).toEqual([ " 2 notes · alt+n expand · last: nested note", ]); await command.handler("rm 1", runner.createCommandContext()); expect(renderLatestWidget()).toEqual([ " 1 notes · alt+n expand · last: nested note", ]); }); it("keeps the source note when a transition is cancelled or busy", async () => { t = await createTestSession({ extensions: [extensionPath()] }); await noteCommand("add stable note"); const runner = t.session.extensionRunner; const command = runner.extensions[0].commands.get("note"); const cancelled = runner.createCommandContext() as any; cancelled.newSession = vi.fn(async () => ({ cancelled: true })); await command.handler("new 1", cancelled); const busy = runner.createCommandContext() as any; busy.isIdle = () => false; busy.newSession = vi.fn(); await command.handler("new 1", busy); expect(renderLatestWidget()).toEqual([ " 1 notes · alt+n expand · last: stable note", ]); expect(busy.newSession).not.toHaveBeenCalled(); expect(uiArgs("notify").at(-1)).toEqual([ "Cannot new while the agent is busy", "warning", ]); }); it("rejects a persisted source that has not been saved yet", async () => { t = await createTestSession({ extensions: [extensionPath()] }); await noteCommand("add stable note"); const runner = t.session.extensionRunner; const command = runner.extensions[0].commands.get("note"); const base = runner.createCommandContext() as any; const sessionManager = Object.create(base.sessionManager); sessionManager.getSessionFile = () => join(t.cwd, "not-created.jsonl"); const ctx = Object.create(base); Object.defineProperty(ctx, "sessionManager", { value: sessionManager }); ctx.newSession = vi.fn(); await command.handler("new 1", ctx); expect(ctx.newSession).not.toHaveBeenCalled(); expect(uiArgs("notify").at(-1)).toEqual([ "Current session is not saved yet; wait for the first assistant response", "warning", ]); expect(renderLatestWidget()).toEqual([ " 1 notes · alt+n expand · last: stable note", ]); }); expect(command.getArgumentCompletions("clone 1")).toEqual([ { value: "clone 1", label: "1 consider split parser tests" }, ]); expect(command.getArgumentCompletions("fork 2")).toEqual([ { value: "fork 2", label: "2 ask whether command should support autocomplete", }, ]); expect(command.getArgumentCompletions("new 1")).toEqual([ { value: "new 1", label: "1 consider split parser tests" }, ]); key: "legacy:2:1", expect(__test.pendingNotes(state)).toEqual([{ id: 3, text: "three" }]); expect(__test.pendingNotes(state)).toEqual([{ id: 2, text: "ok" }]); key: expect.any(String),+413 / −14 text lines
const NOTE_LAUNCH = Symbol.for("@bugabinga/pi-ext-notes/launch"); | { op: "add"; id: number; text: string; createdAt: number } | { op: "add"; id: number; key?: string; text: string; createdAt: number } id?: unknown; message?: unknown;type NoteLaunchKind = "clone" | "fork" | "new";type DestinationReceiver = { instanceToken: string; consume(): boolean; fail(message: string): void; revoke(): void;};type ReplacementContext = ExtensionCommandContext & { sendUserMessage( content: string, options?: { expandPromptTemplates?: boolean }, ): Promise<void>;};type NoteLaunch = { token: string; sourceInstanceToken: string; sourceSessionId: string; kind: NoteLaunchKind; note: Note; sourceLeafId?: string; sourceSessionFile?: string; targetSessionFile?: string; shutdownSeen: boolean; destinationClaimed: boolean; replacementContext?: ReplacementContext; receiver?: DestinationReceiver;}; key: isNonEmptyText(event.key) ? event.key.trim() : undefined, state.notes.set(event.id, { id: event.id, text: event.text }); state.notes.set(event.id, { id: event.id, text: event.text }); state.notes.set(event.id, { ...note, text: event.text });function activeLaunch(): NoteLaunch | undefined { const launch = Reflect.get(globalThis, NOTE_LAUNCH); return launch && typeof launch === "object" ? (launch as NoteLaunch) : undefined;}function startLaunch(launch: NoteLaunch): boolean { if (activeLaunch()) return false; Reflect.set(globalThis, NOTE_LAUNCH, launch); return true;}function finishLaunch(launch: NoteLaunch): void { if (activeLaunch()?.token === launch.token) { Reflect.deleteProperty(globalThis, NOTE_LAUNCH); }}function launchReason(kind: NoteLaunchKind): "fork" | "new" { return kind === "new" ? "new" : "fork";}const SUBCOMMANDS = ["add", "send", "edit", "rm", "clear"] as const;function messageText(content: unknown): string { if (typeof content === "string") return content; if (!Array.isArray(content)) return ""; return content .filter( (part): part is { type: "text"; text: string } => part !== null && typeof part === "object" && Reflect.get(part, "type") === "text" && typeof Reflect.get(part, "text") === "string", ) .map((part) => part.text) .join("");}function userMessagesForForking( entries: SessionEntryLike[],): Array<{ entryId: string; text: string }> { const messages: Array<{ entryId: string; text: string }> = []; for (const entry of entries) { if (entry.type !== "message" || typeof entry.id !== "string") continue; if (!entry.message || typeof entry.message !== "object") continue; if (Reflect.get(entry.message, "role") !== "user") continue; const text = messageText(Reflect.get(entry.message, "content")); if (text) messages.push({ entryId: entry.id, text }); } return messages;}async function selectForkEntry( ctx: ExtensionCommandContext,): Promise<string | undefined> { if (ctx.mode !== "tui") { notify(ctx, "Note fork requires Pi's interactive TUI", "warning"); return undefined; } const messages = userMessagesForForking( ctx.sessionManager.getEntries() as SessionEntryLike[], ); if (messages.length === 0) { notify(ctx, "No messages to fork from", "info"); return undefined; } const initialSelectedId = messages.at(-1)?.entryId; return ctx.ui.custom<string | undefined>( (tui, _theme, _keybindings, done) => { const selector = new UserMessageSelectorComponent( messages.map(({ entryId, text }) => ({ id: entryId, text })), done, () => done(undefined), initialSelectedId, ); const list = selector.getMessageList(); return { invalidate: () => selector.invalidate(), render: (width: number) => selector.render(width), handleInput(keyData: string) { list.handleInput(keyData); tui.requestRender(); }, }; }, );}function consumeSourceNote(launch: NoteLaunch): void { const { sourceSessionFile, sourceLeafId } = launch; if (!sourceSessionFile || !existsSync(sourceSessionFile)) return; const manager = SessionManager.open(sourceSessionFile); if (manager.getSessionId() !== launch.sourceSessionId) { throw new Error("Source session identity changed before note consumption"); } if (sourceLeafId) manager.branch(sourceLeafId); else manager.resetLeaf(); const sourceState = replayNotes(manager.getBranch() as SessionEntryLike[]); const note = noteWithKey(sourceState, launch.note.key); if (!note) { throw new Error("Source note changed before it could be consumed"); } manager.appendCustomEntry(ENTRY_TYPE, { op: "remove", id: note.id, removedAt: Date.now(), } satisfies NotesEvent);}function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error);}const SUBCOMMANDS = [ "add", "send", "clone", "fork", "new", "edit", "rm", "clear",] as const; if (command !== "send" && command !== "edit" && command !== "rm") return []; function rejectReservedNote(ctx: ExtensionContext, note: Note): boolean { if (!reservedNoteKeys.has(note.key)) return false; notify(ctx, `Note ${note.id} is being delivered`, "warning"); return true; } function stageLaunch(ctx: ExtensionContext, launch: NoteLaunch): void { let staged = noteWithKey(state, launch.note.key); if (!staged) { appendEvent(pi, state, { op: "add", id: state.nextId, key: launch.note.key, text: launch.note.text, createdAt: Date.now(), }); staged = noteWithKey(state, launch.note.key); } else if (staged.text !== launch.note.text) { appendEvent(pi, state, { op: "edit", id: staged.id, text: launch.note.text, updatedAt: Date.now(), }); staged = noteWithKey(state, launch.note.key); } if (!staged) throw new Error("Failed to stage note in destination session"); reservedNoteKeys.add(launch.note.key); refreshWidget(ctx); let active = true; launch.receiver = { instanceToken, consume() { if (!active) return false; const note = noteWithKey(state, launch.note.key); if (!note) { reservedNoteKeys.delete(launch.note.key); return false; } appendEvent(pi, state, { op: "remove", id: note.id, removedAt: Date.now(), }); reservedNoteKeys.delete(launch.note.key); refreshWidget(ctx); return true; }, fail(message) { if (!active) return; reservedNoteKeys.delete(launch.note.key); notify(ctx, `Note remains pending: ${message}`, "error"); refreshWidget(ctx); }, revoke() { active = false; reservedNoteKeys.delete(launch.note.key); }, }; } async function launchNote( kind: NoteLaunchKind, note: Note, ctx: ExtensionCommandContext, ): Promise<void> { if (!ctx.isIdle() || ctx.hasPendingMessages()) { notify(ctx, `Cannot ${kind} while the agent is busy`, "warning"); return; } if (activeLaunch()) { notify(ctx, "Another note session transition is active", "warning"); return; } const sourceSessionFile = ctx.sessionManager.getSessionFile() ?? undefined; if (sourceSessionFile && !existsSync(sourceSessionFile)) { notify( ctx, "Current session is not saved yet; wait for the first assistant response", "warning", ); return; } let targetEntryId: string | undefined; if (kind === "fork") { targetEntryId = await selectForkEntry(ctx); if (!targetEntryId) return; if (!ctx.isIdle() || ctx.hasPendingMessages()) { notify(ctx, "Cannot fork while the agent is busy", "warning"); return; } const currentNote = state.notes.get(note.id); if (currentNote?.key !== note.key || currentNote.text !== note.text) { notify( ctx, `Note ${note.id} changed while selecting a fork`, "warning", ); return; } } const sourceLeafId = ctx.sessionManager.getLeafId() ?? undefined; if (kind === "clone" && !sourceLeafId) { notify(ctx, "Nothing to clone yet", "info"); return; } const launch: NoteLaunch = { token: crypto.randomUUID(), sourceInstanceToken: instanceToken, sourceSessionId: ctx.sessionManager.getSessionId(), kind, note: structuredClone(note), sourceLeafId, sourceSessionFile, shutdownSeen: false, destinationClaimed: false, }; if (!startLaunch(launch)) { notify(ctx, "Another note session transition is active", "warning"); return; } try { const withSession = async (replacement: ReplacementContext) => { launch.replacementContext = replacement; }; const result = kind === "new" ? await ctx.newSession({ withSession }) : await ctx.fork(targetEntryId ?? sourceLeafId ?? "", { position: kind === "clone" ? "at" : "before", withSession, }); if (result.cancelled) return; const replacement = launch.replacementContext; const receiver = launch.receiver; if (!replacement || !receiver) { replacement?.ui.notify( "Note session transition completed without a destination handoff", "error", ); return; } replacement.ui.setEditorText(""); try { await replacement.sendUserMessage(launch.note.text, { expandPromptTemplates: true, }); } catch (error) { receiver.fail(errorMessage(error)); return; } try { if (!receiver.consume()) return; } catch (error) { receiver.fail(errorMessage(error)); return; } try { consumeSourceNote(launch); } catch (error) { replacement.ui.notify( `Note delivered; source copy remains pending: ${errorMessage(error)}`, "warning", ); } } finally { finishLaunch(launch); } } description: "Park, inspect, edit, send, or clear pending prompt notes.", description: "Park, edit, send, or launch sessions from prompt notes.", key: crypto.randomUUID(), notify(ctx, "Usage: /note [add|send|edit|rm|clear]", "warning"); if (command === "clone" || command === "fork" || command === "new") { const note = requireNote(ctx, state, rest); if (!note || rejectReservedNote(ctx, note)) return; await launchNote(command, note, ctx); return; } notify( ctx, "Usage: /note [add|send|clone|fork|new|edit|rm|clear]", "warning", ); const launch = activeLaunch(); if (launch?.receiver?.instanceToken === instanceToken) { launch.receiver.revoke(); } if ( launch?.sourceInstanceToken === instanceToken && !launch.shutdownSeen && event.reason === launchReason(launch.kind) ) { launch.shutdownSeen = true; launch.targetSessionFile = event.targetSessionFile; return; } const launch = activeLaunch(); if ( launch?.shutdownSeen && !launch.destinationClaimed && event.reason === launchReason(launch.kind) && event.previousSessionFile === launch.sourceSessionFile && ctx.sessionManager.getSessionFile() === launch.targetSessionFile ) { launch.destinationClaimed = true; stageLaunch(ctx, launch); return; } key: note.key, clearLaunch: () => Reflect.deleteProperty(globalThis, NOTE_LAUNCH), userMessagesForForking,+9 / −0 text lines