confirm-destructive.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * Confirm Destructive Actions Extension
  3. *
  4. * Prompts for confirmation before destructive session actions (clear, switch, branch).
  5. * Demonstrates how to cancel session events using the before_* events.
  6. */
  7. import type { ExtensionAPI, SessionBeforeSwitchEvent, SessionMessageEntry } from "@earendil-works/pi-coding-agent";
  8. export default function (pi: ExtensionAPI) {
  9. pi.on("session_before_switch", async (event: SessionBeforeSwitchEvent, ctx) => {
  10. if (!ctx.hasUI) return;
  11. if (event.reason === "new") {
  12. const confirmed = await ctx.ui.confirm(
  13. "Clear session?",
  14. "This will delete all messages in the current session.",
  15. );
  16. if (!confirmed) {
  17. ctx.ui.notify("Clear cancelled", "info");
  18. return { cancel: true };
  19. }
  20. return;
  21. }
  22. // reason === "resume" - check if there are unsaved changes (messages since last assistant response)
  23. const entries = ctx.sessionManager.getEntries();
  24. const hasUnsavedWork = entries.some(
  25. (e): e is SessionMessageEntry => e.type === "message" && e.message.role === "user",
  26. );
  27. if (hasUnsavedWork) {
  28. const confirmed = await ctx.ui.confirm(
  29. "Switch session?",
  30. "You have messages in the current session. Switch anyway?",
  31. );
  32. if (!confirmed) {
  33. ctx.ui.notify("Switch cancelled", "info");
  34. return { cancel: true };
  35. }
  36. }
  37. });
  38. pi.on("session_before_fork", async (event, ctx) => {
  39. if (!ctx.hasUI) return;
  40. const choice = await ctx.ui.select(`Fork from entry ${event.entryId.slice(0, 8)}?`, [
  41. "Yes, create fork",
  42. "No, stay in current session",
  43. ]);
  44. if (choice !== "Yes, create fork") {
  45. ctx.ui.notify("Fork cancelled", "info");
  46. return { cancel: true };
  47. }
  48. });
  49. }