timed-confirm.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Example extension demonstrating timed dialogs with live countdown.
  3. *
  4. * Commands:
  5. * - /timed - Shows confirm dialog that auto-cancels after 5 seconds with countdown
  6. * - /timed-select - Shows select dialog that auto-cancels after 10 seconds with countdown
  7. * - /timed-signal - Shows confirm using AbortSignal (manual approach)
  8. */
  9. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  10. export default function (pi: ExtensionAPI) {
  11. // Simple approach: use timeout option (recommended)
  12. pi.registerCommand("timed", {
  13. description: "Show a timed confirmation dialog (auto-cancels in 5s with countdown)",
  14. handler: async (_args, ctx) => {
  15. const confirmed = await ctx.ui.confirm(
  16. "Timed Confirmation",
  17. "This dialog will auto-cancel in 5 seconds. Confirm?",
  18. { timeout: 5000 },
  19. );
  20. if (confirmed) {
  21. ctx.ui.notify("Confirmed by user!", "info");
  22. } else {
  23. ctx.ui.notify("Cancelled or timed out", "info");
  24. }
  25. },
  26. });
  27. pi.registerCommand("timed-select", {
  28. description: "Show a timed select dialog (auto-cancels in 10s with countdown)",
  29. handler: async (_args, ctx) => {
  30. const choice = await ctx.ui.select("Pick an option", ["Option A", "Option B", "Option C"], { timeout: 10000 });
  31. if (choice) {
  32. ctx.ui.notify(`Selected: ${choice}`, "info");
  33. } else {
  34. ctx.ui.notify("Selection cancelled or timed out", "info");
  35. }
  36. },
  37. });
  38. // Manual approach: use AbortSignal for more control
  39. pi.registerCommand("timed-signal", {
  40. description: "Show a timed confirm using AbortSignal (manual approach)",
  41. handler: async (_args, ctx) => {
  42. const controller = new AbortController();
  43. const timeoutId = setTimeout(() => controller.abort(), 5000);
  44. ctx.ui.notify("Dialog will auto-cancel in 5 seconds...", "info");
  45. const confirmed = await ctx.ui.confirm(
  46. "Timed Confirmation",
  47. "This dialog will auto-cancel in 5 seconds. Confirm?",
  48. { signal: controller.signal },
  49. );
  50. clearTimeout(timeoutId);
  51. if (confirmed) {
  52. ctx.ui.notify("Confirmed by user!", "info");
  53. } else if (controller.signal.aborted) {
  54. ctx.ui.notify("Dialog timed out (auto-cancelled)", "warning");
  55. } else {
  56. ctx.ui.notify("Cancelled by user", "info");
  57. }
  58. },
  59. });
  60. }