pi-tui-status-beautifier 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -99,6 +99,7 @@ const BRACKET_PATTERN = /\[(\d+)\]/;
99
99
  const NUMBER_PATTERN = /\b(\d+)\b/;
100
100
 
101
101
  let currentStyle = "minimal";
102
+ let fullFooterEnabled = false;
102
103
  let customStyleConfig: CustomStyleConfig | undefined;
103
104
 
104
105
  /**
@@ -107,6 +108,7 @@ let customStyleConfig: CustomStyleConfig | undefined;
107
108
  */
108
109
  export function loadConfig(cwd: string = process.cwd()): {
109
110
  style: string;
111
+ fullFooter: boolean;
110
112
  custom?: CustomStyleConfig;
111
113
  targetSettingsPath: string;
112
114
  } {
@@ -115,6 +117,7 @@ export function loadConfig(cwd: string = process.cwd()): {
115
117
  const localPath = path.join(cwd, ".pi/settings.json");
116
118
 
117
119
  let resolvedStyle = "minimal";
120
+ let resolvedFullFooter = false;
118
121
  let resolvedCustom: CustomStyleConfig | undefined;
119
122
  let hasLocalConfig = false;
120
123
 
@@ -131,6 +134,9 @@ export function loadConfig(cwd: string = process.cwd()): {
131
134
  resolvedStyle = s;
132
135
  }
133
136
  }
137
+ if (typeof data.beautifier.fullFooter === "boolean") {
138
+ resolvedFullFooter = data.beautifier.fullFooter;
139
+ }
134
140
  if (data.beautifier.custom && typeof data.beautifier.custom === "object") {
135
141
  resolvedCustom = data.beautifier.custom;
136
142
  }
@@ -152,6 +158,9 @@ export function loadConfig(cwd: string = process.cwd()): {
152
158
  resolvedStyle = s;
153
159
  }
154
160
  }
161
+ if (typeof data.beautifier.fullFooter === "boolean") {
162
+ resolvedFullFooter = data.beautifier.fullFooter;
163
+ }
155
164
  if (data.beautifier.custom && typeof data.beautifier.custom === "object") {
156
165
  resolvedCustom = { ...(resolvedCustom || {}), ...data.beautifier.custom };
157
166
  }
@@ -160,11 +169,12 @@ export function loadConfig(cwd: string = process.cwd()): {
160
169
  } catch (_) {}
161
170
 
162
171
  currentStyle = resolvedStyle;
172
+ fullFooterEnabled = resolvedFullFooter;
163
173
  customStyleConfig = resolvedCustom;
164
174
 
165
175
  // Target path for atomic write: local project if exists or in project directory, otherwise global
166
176
  const targetSettingsPath = hasLocalConfig || fs.existsSync(localPath) ? localPath : globalPath;
167
- return { style: resolvedStyle, custom: resolvedCustom, targetSettingsPath };
177
+ return { style: resolvedStyle, fullFooter: resolvedFullFooter, custom: resolvedCustom, targetSettingsPath };
168
178
  }
169
179
 
170
180
  loadConfig();
@@ -466,26 +476,66 @@ export function renderBeautifiedFooter(
466
476
  const modelName = ctx?.model?.name || ctx?.model?.id || "";
467
477
  const styledModel = modelName ? (hasThemeFg ? theme.fg("muted", modelName) : modelName) : "";
468
478
 
469
- // 3. Token metrics
470
- let input = 0, output = 0;
471
- if (ctx?.sessionManager?.getBranch) {
479
+ // 3. Token metrics & context usage (full fidelity matching native Pi footer)
480
+ let input = 0, output = 0, cacheRead = 0, cacheWrite = 0, cost = 0;
481
+ let latestCacheHitRate: number | undefined;
482
+
483
+ if (ctx?.sessionManager?.getEntries) {
472
484
  try {
473
- for (const e of ctx.sessionManager.getBranch()) {
474
- if (e.type === "message" && e.message?.role === "assistant" && e.message?.usage) {
475
- const u = e.message.usage;
485
+ for (const entry of ctx.sessionManager.getEntries()) {
486
+ if (entry.type === "usage" && entry.usage) {
487
+ input += entry.usage.input || 0;
488
+ output += entry.usage.output || 0;
489
+ cacheRead += entry.usage.cacheRead || 0;
490
+ cacheWrite += entry.usage.cacheWrite || 0;
491
+ cost += entry.usage.cost?.total || 0;
492
+ } else if (entry.type === "message" && entry.message?.role === "assistant" && entry.message?.usage) {
493
+ const u = entry.message.usage;
476
494
  input += u.input || 0;
477
495
  output += u.output || 0;
496
+ cacheRead += u.cacheRead || 0;
497
+ cacheWrite += u.cacheWrite || 0;
498
+ cost += u.cost?.total || 0;
499
+ const promptTokens = (u.input || 0) + (u.cacheRead || 0) + (u.cacheWrite || 0);
500
+ if (promptTokens > 0 && u.cacheRead) {
501
+ latestCacheHitRate = (u.cacheRead / promptTokens) * 100;
502
+ }
478
503
  }
479
504
  }
480
505
  } catch (_) {}
481
506
  }
482
- const fmt = (n: number) => (n < 1000 ? `${n}` : `${(n / 1000).toFixed(1)}k`);
483
- const tokenStr = input > 0 || output > 0 ? `↑${fmt(input)} ↓${fmt(output)}` : "";
507
+
508
+ const fmt = (n: number) => {
509
+ if (n < 1000) return `${n}`;
510
+ if (n < 10000) return `${(n / 1000).toFixed(1)}k`;
511
+ if (n < 1000000) return `${Math.round(n / 1000)}k`;
512
+ if (n < 10000000) return `${(n / 1000000).toFixed(1)}M`;
513
+ return `${Math.round(n / 1000000)}M`;
514
+ };
515
+
516
+ const statParts: string[] = [];
517
+ if (input > 0) statParts.push(`↑${fmt(input)}`);
518
+ if (output > 0) statParts.push(`↓${fmt(output)}`);
519
+ if (cacheRead > 0) statParts.push(`R${fmt(cacheRead)}`);
520
+ if (latestCacheHitRate !== undefined) statParts.push(`CH${latestCacheHitRate.toFixed(1)}%`);
521
+ if (cost > 0) statParts.push(`$${cost.toFixed(3)}`);
522
+
523
+ const contextUsage = ctx?.getContextUsage?.();
524
+ const contextWindow = contextUsage?.contextWindow || ctx?.model?.contextWindow || 0;
525
+ if (contextUsage?.percent !== undefined && contextUsage?.percent !== null) {
526
+ statParts.push(`${contextUsage.percent.toFixed(1)}%/${fmt(contextWindow)} (auto)`);
527
+ }
528
+
529
+ const tokenStr = statParts.join(" ");
484
530
  const styledTokens = tokenStr ? (hasThemeFg ? theme.fg("dim", tokenStr) : tokenStr) : "";
485
531
 
532
+ // Thinking level
533
+ const thinking = ctx?.thinkingLevel && ctx.thinkingLevel !== "off" ? ` • ${ctx.thinkingLevel}` : "";
534
+ const fullModelStr = styledModel ? `${styledModel}${hasThemeFg ? theme.fg("dim", thinking) : thinking}` : "";
535
+
486
536
  // Left & right parts of Line 1
487
537
  const leftText = styledBranch;
488
- const rightParts = [styledTokens, styledModel].filter(Boolean);
538
+ const rightParts = [styledTokens, fullModelStr].filter(Boolean);
489
539
  const rightText = rightParts.join(styledSep);
490
540
 
491
541
  const leftVis = getStringWidth(leftText);
@@ -534,7 +584,7 @@ export default function (pi: ExtensionAPI) {
534
584
  originalStatuses.clear();
535
585
  lastRenderedStatus.clear();
536
586
 
537
- // Hook setStatus for clean status badge formatting (never hijack Pi's native footer)
587
+ // 1. Hook setStatus for clean status badge formatting (always active unless style === "off")
538
588
  const originalSetStatus = ctx.ui.setStatus;
539
589
  if (originalSetStatus && !(originalSetStatus as any).__beautifierHooked) {
540
590
  const wrapped = function (key: string, value: string | undefined) {
@@ -553,42 +603,68 @@ export default function (pi: ExtensionAPI) {
553
603
  (wrapped as any).__beautifierHooked = true;
554
604
  ctx.ui.setStatus = wrapped;
555
605
  }
606
+
607
+ // 2. Hook setFooter ONLY if user explicitly opted in with fullFooter === true!
608
+ // By default fullFooter is FALSE: Pi's native top two lines remain 100% native and untouched!
609
+ if (fullFooterEnabled && currentStyle !== "off" && typeof (ctx.ui as any).setFooter === "function") {
610
+ (ctx.ui as any).setFooter((tui: any, theme: any, footerData: any) => {
611
+ const unsub =
612
+ typeof footerData?.onBranchChange === "function"
613
+ ? footerData.onBranchChange(() => tui.requestRender())
614
+ : undefined;
615
+
616
+ return {
617
+ dispose: unsub,
618
+ invalidate() {},
619
+ render(width: number): string[] {
620
+ if (currentStyle === "off" || !fullFooterEnabled) return [];
621
+ return renderBeautifiedFooter(width, tui, theme, footerData, ctx, currentStyle, customStyleConfig);
622
+ },
623
+ };
624
+ });
625
+ } else if (typeof (ctx.ui as any).setFooter === "function") {
626
+ (ctx.ui as any).setFooter(undefined); // Restore native Pi footer
627
+ }
556
628
  });
557
629
 
558
630
  // Dynamic status bar style controller registry
559
631
  pi.registerCommand("beautify", {
560
- description: "Choose TUI status bar beautification style or generate a custom style with AI",
632
+ description: "Choose TUI status bar style or customize with AI",
561
633
  handler: async (_args, ctx) => {
562
634
  if (!ctx.hasUI || !ctx.ui) {
563
635
  return;
564
636
  }
565
637
 
638
+ // Stage 1: Select Style / Theme
566
639
  const styleOptions = [
567
640
  "stream - Clean chevron stream (e.g. name ❯ ● ready)",
568
641
  "powerline - Angled brackets & diamonds (e.g. name ‹◆ ready›)",
569
642
  "matrix - Dot-matrix brackets & stars (e.g. name ⦗✦ ready⦘)",
570
643
  "glow - High-contrast inverse pill (e.g. name [ ● ready ])",
571
- "custom - [AI Prompt Recipe] Let your agent tailor your bespoke style",
644
+ "custom - Describe your custom aesthetic to AI",
572
645
  "off - Revert to native Pi status bar & clean settings",
573
646
  ];
574
647
 
575
- const choice = await ctx.ui.select(`Choose status style (Current: ${currentStyle}):`, styleOptions);
648
+ const choice = await ctx.ui.select(`Choose status bar style (Current: ${currentStyle}):`, styleOptions);
576
649
 
577
650
  if (!choice) return;
578
651
 
579
652
  const styleKey = choice.split(" ")[0].trim();
580
653
 
654
+ // Zero-trace physical cleanup & revert
581
655
  if (styleKey === "off") {
582
656
  currentStyle = "off";
657
+ fullFooterEnabled = false;
583
658
  customStyleConfig = undefined;
584
659
  lastRenderedStatus.clear();
585
660
 
586
- // Restore all raw original statuses immediately
587
661
  for (const [key, val] of originalStatuses.entries()) {
588
662
  ctx.ui.setStatus(key, val);
589
663
  }
664
+ if (typeof (ctx.ui as any).setFooter === "function") {
665
+ (ctx.ui as any).setFooter(undefined);
666
+ }
590
667
 
591
- // Zero-trace physical cleanup: completely prune the `beautifier` key from settings.json!
592
668
  const { targetSettingsPath } = loadConfig(ctx.cwd || process.cwd());
593
669
  try {
594
670
  if (fs.existsSync(targetSettingsPath)) {
@@ -609,41 +685,113 @@ export default function (pi: ExtensionAPI) {
609
685
  return;
610
686
  }
611
687
 
688
+ // Form A: Interactive plain-language input dialog for Custom Style
612
689
  if (styleKey === "custom") {
613
- const promptRecipe = [
614
- "You are acting as my Pi TUI Status Bar designer for `pi-tui-status-beautifier`.",
615
- "1. In my primary language, call `ask_user_question` with ASCII visual preview mockups showing ONLY realistic extension statuses (e.g. `chrome`, `toolflow`, `plan`):",
616
- " - Powerline: chrome ‹◆ ready› | toolflow ‹◈ 2/5›",
617
- " - Matrix: chrome ⦗✦ ready⦘ | toolflow ⦗◍ 2/5⦘",
618
- " - Stream: chrome ❯ ● ready | toolflow ❯ ◐ 2/5",
619
- " - Glow: chrome [ ● ready ] | toolflow [ ◐ 2/5 ]",
620
- " (Do NOT include git branch or model name in mockups).",
621
- "2. If I describe or pick a style, write the configuration into `./.pi/settings.json` (or `~/.pi/agent/settings.json`) under `beautifier`:",
690
+ let userDesire: string | undefined;
691
+ if (typeof (ctx.ui as any).input === "function") {
692
+ userDesire = await (ctx.ui as any).input(
693
+ "Describe your custom status bar style:",
694
+ "e.g. 赛博复古点阵 / Minimal dots / Soft warm pastel / Powerline diamonds"
695
+ );
696
+ }
697
+
698
+ if (!userDesire || !userDesire.trim()) {
699
+ return;
700
+ }
701
+
702
+ const instruction = [
703
+ "Please configure a custom Pi TUI status bar style for `pi-tui-status-beautifier`.",
704
+ `User's requested aesthetic: "${userDesire.trim()}"`,
705
+ "",
706
+ "Requirements:",
707
+ `1. In the user's primary language, call \`ask_user_question\` with 3 distinct ASCII visual preview mockups tailored to "${userDesire.trim()}". Show ONLY realistic extension status items (e.g. \`chrome\`, \`toolflow\`, \`plan\`). Do NOT include git branch or model name in mockups.`,
708
+ "2. Once selected, save the configuration into `./.pi/settings.json` (or `~/.pi/agent/settings.json`) under `beautifier`:",
622
709
  " {",
623
710
  ' "beautifier": {',
624
711
  ' "style": "custom",',
625
712
  ' "custom": {',
626
- ' "separator": " » ",',
627
- ' "brackets": ["«", "»"],',
628
- ' "prefix": "",',
629
- ' "suffix": "",',
630
- ' "glyphs": { "success": "✦", "warning": "◇", "error": "✖", "accent": "✧" }',
713
+ ' "separator": " ... ",',
714
+ ' "brackets": ["...", "..."],',
715
+ ' "prefix": "...",',
716
+ ' "suffix": "...",',
717
+ ' "glyphs": { "success": "...", "warning": "...", "error": "...", "accent": "..." }',
631
718
  " }",
632
719
  " }",
633
720
  " }",
634
- "3. If I say revert, restore, default, off, or cancel, DELETE the `beautifier` key from `settings.json` and exit quietly without asking more questions.",
635
- "4. Do NOT search filesystem or edit extension source files."
721
+ "3. If the user ever asks to revert, cancel, or restore default, cleanly delete `beautifier` from `settings.json` without asking questions.",
722
+ "4. Do NOT search the filesystem or edit extension source files. Confirm when applied."
636
723
  ].join("\n");
637
724
 
638
- if (typeof (ctx.ui as any).setEditorText === "function") {
639
- (ctx.ui as any).setEditorText(promptRecipe);
640
- ctx.ui.notify("Press Enter to let your agent consult your style preference with visual previews!", "info");
641
- } else {
642
- ctx.ui.notify(promptRecipe, "info");
725
+ if (typeof (pi as any).sendUserMessage === "function") {
726
+ (pi as any).sendUserMessage(instruction, { deliverAs: "followUp" });
727
+ ctx.ui.notify("Consulting AI status bar designer...", "info");
728
+ } else if (typeof (ctx.ui as any).setEditorText === "function") {
729
+ (ctx.ui as any).setEditorText(instruction);
730
+ ctx.ui.notify("Press Enter to send custom style request to your agent!", "info");
643
731
  }
644
732
  return;
645
733
  }
646
734
 
735
+ // Stage 2: Scope Selection Wizard (Two-stage flow)
736
+ const scopeOptions = [
737
+ "status-only - Plugin status badges only (Recommended: keeps native Pi path, tokens & thinking level)",
738
+ "full-footer - Full-footer beautification (Transforms Git branch, model, and tokens too)",
739
+ ];
740
+
741
+ const scopeChoice = await ctx.ui.select("Choose beautification scope:", scopeOptions);
742
+ if (!scopeChoice) return;
743
+
744
+ const isFullFooter = scopeChoice.startsWith("full-footer");
745
+ fullFooterEnabled = isFullFooter;
746
+ currentStyle = styleKey;
747
+ lastRenderedStatus.clear();
748
+
749
+ // Write atomically to settings.json
750
+ const { targetSettingsPath } = loadConfig(ctx.cwd || process.cwd());
751
+ try {
752
+ if (fs.existsSync(targetSettingsPath)) {
753
+ const data = fs.readFileSync(targetSettingsPath, "utf-8");
754
+ const config = JSON.parse(data);
755
+ if (!config.beautifier) config.beautifier = {};
756
+ config.beautifier.style = styleKey;
757
+ config.beautifier.fullFooter = isFullFooter;
758
+ const tempSettings = `${targetSettingsPath}.tmp.${process.pid}.${Date.now()}`;
759
+ fs.writeFileSync(tempSettings, JSON.stringify(config, null, 2), "utf-8");
760
+ fs.renameSync(tempSettings, targetSettingsPath);
761
+ }
762
+ } catch (_e) {
763
+ // Silently ignore disk write errors
764
+ }
765
+
766
+ // Update footer rendering
767
+ if (isFullFooter && typeof (ctx.ui as any).setFooter === "function") {
768
+ (ctx.ui as any).setFooter((tui: any, theme: any, footerData: any) => {
769
+ const unsub =
770
+ typeof footerData?.onBranchChange === "function"
771
+ ? footerData.onBranchChange(() => tui.requestRender())
772
+ : undefined;
773
+ return {
774
+ dispose: unsub,
775
+ invalidate() {},
776
+ render(width: number): string[] {
777
+ if (currentStyle === "off" || !fullFooterEnabled) return [];
778
+ return renderBeautifiedFooter(width, tui, theme, footerData, ctx, currentStyle, customStyleConfig);
779
+ },
780
+ };
781
+ });
782
+ } else if (typeof (ctx.ui as any).setFooter === "function") {
783
+ (ctx.ui as any).setFooter(undefined);
784
+ }
785
+
786
+ for (const [key, val] of originalStatuses.entries()) {
787
+ ctx.ui.setStatus(key, val);
788
+ }
789
+
790
+ ctx.ui.notify(
791
+ `TUI status style changed to: ${styleKey} (${isFullFooter ? "Full-Footer" : "Status Only"})`,
792
+ "info"
793
+ );
794
+
647
795
  if ((VALID_STYLES as readonly string[]).includes(styleKey)) {
648
796
  currentStyle = styleKey;
649
797
  lastRenderedStatus.clear();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tui-status-beautifier",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "description": "Minimalist status bar formatter & AI-customizable layout engine for Pi TUI.",
5
5
  "main": "extensions/tui-status-beautifier.ts",
6
6
  "keywords": [