custom-footer.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Custom Footer Extension - demonstrates ctx.ui.setFooter()
  3. *
  4. * footerData exposes data not otherwise accessible:
  5. * - getGitBranch(): current git branch
  6. * - getExtensionStatuses(): texts from ctx.ui.setStatus()
  7. *
  8. * Token stats come from ctx.sessionManager/ctx.model (already accessible).
  9. */
  10. import type { AssistantMessage } from "@earendil-works/pi-ai";
  11. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  12. import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
  13. export default function (pi: ExtensionAPI) {
  14. let enabled = false;
  15. pi.registerCommand("footer", {
  16. description: "Toggle custom footer",
  17. handler: async (_args, ctx) => {
  18. enabled = !enabled;
  19. if (enabled) {
  20. ctx.ui.setFooter((tui, theme, footerData) => {
  21. const unsub = footerData.onBranchChange(() => tui.requestRender());
  22. return {
  23. dispose: unsub,
  24. invalidate() {},
  25. render(width: number): string[] {
  26. // Compute tokens from ctx (already accessible to extensions)
  27. let input = 0,
  28. output = 0,
  29. cost = 0;
  30. for (const e of ctx.sessionManager.getBranch()) {
  31. if (e.type === "message" && e.message.role === "assistant") {
  32. const m = e.message as AssistantMessage;
  33. input += m.usage.input;
  34. output += m.usage.output;
  35. cost += m.usage.cost.total;
  36. }
  37. }
  38. // Get git branch (not otherwise accessible)
  39. const branch = footerData.getGitBranch();
  40. const fmt = (n: number) => (n < 1000 ? `${n}` : `${(n / 1000).toFixed(1)}k`);
  41. const left = theme.fg("dim", `↑${fmt(input)} ↓${fmt(output)} $${cost.toFixed(3)}`);
  42. const branchStr = branch ? ` (${branch})` : "";
  43. const right = theme.fg("dim", `${ctx.model?.id || "no-model"}${branchStr}`);
  44. const pad = " ".repeat(Math.max(1, width - visibleWidth(left) - visibleWidth(right)));
  45. return [truncateToWidth(left + pad + right, width)];
  46. },
  47. };
  48. });
  49. ctx.ui.notify("Custom footer enabled", "info");
  50. } else {
  51. ctx.ui.setFooter(undefined);
  52. ctx.ui.notify("Default footer restored", "info");
  53. }
  54. },
  55. });
  56. }