Commit 276768f3eb4f

Vincent Demeester <vincent@sbr.pm>
2026-10-22 16:16:33
feat: streamline Pi footer status
Reduced persistent footer noise while surfacing cache efficiency and context handoff signals before sessions become expensive or resume with cold caches. Signed-off-by: Vincent Demeester <vincent@sbr.pm>
1 parent 7de7874
Changed files (3)
dots
dots/pi/agent/extensions/org-todos/index.ts
@@ -887,8 +887,6 @@ export default function (pi: ExtensionAPI) {
         display: true,
       });
 
-      // Update today status as completing a task affects the count
-      updateTodayStatus(ctx);
     },
   });
 
@@ -1180,11 +1178,6 @@ export default function (pi: ExtensionAPI) {
         display: true,
       });
       
-      // Update status bars (inbox count and today if scheduled)
-      updateInboxStatus(ctx);
-      if (parsed.scheduled) {
-        updateTodayStatus(ctx);
-      }
     },
   });
 
@@ -1360,81 +1353,11 @@ export default function (pi: ExtensionAPI) {
         display: true,
       });
       
-      // Update inbox count
-      updateInboxStatus(ctx);
     },
   });
 
-  // Helper function to update inbox count in status bar
-  function updateInboxStatus(ctx: any) {
-    try {
-      const result = execEmacs(`(pi/org-todo-inbox-all)`);
-      
-      if (result.success && Array.isArray(result.data)) {
-        const count = result.data.length;
-        if (count > 0) {
-          ctx.ui.setStatus("inbox-count", ctx.ui.theme.fg("warning", `📥 ${count}`));
-        } else {
-          ctx.ui.setStatus("inbox-count", undefined);
-        }
-      }
-    } catch (e) {
-      // Silently fail - inbox status is not critical
-    }
-  }
-
-  // Helper function to update today's tasks status in status bar
-  function updateTodayStatus(ctx: any) {
-    try {
-      // Get scheduled and overdue counts
-      const scheduledResult = execEmacs("(pi/org-todo-scheduled)");
-      const overdueResult = execEmacs("(pi/org-todo-overdue)");
-      
-      if (scheduledResult.success && overdueResult.success) {
-        const schedCount = Array.isArray(scheduledResult.data) ? scheduledResult.data.length : 0;
-        const overdueCount = Array.isArray(overdueResult.data) ? overdueResult.data.length : 0;
-        
-        if (schedCount === 0 && overdueCount === 0) {
-          // Nothing scheduled or overdue - show clear status
-          ctx.ui.setStatus("today-todos", ctx.ui.theme.fg("success", "✓"));
-        } else if (overdueCount > 0 && schedCount > 0) {
-          // Both overdue and scheduled - show both with overdue in red
-          ctx.ui.setStatus("today-todos", 
-            ctx.ui.theme.fg("error", `⚠️ ${overdueCount}`) + " " + 
-            ctx.ui.theme.fg("accent", `📅 ${schedCount}`));
-        } else if (overdueCount > 0) {
-          // Only overdue - show in red
-          ctx.ui.setStatus("today-todos", 
-            ctx.ui.theme.fg("error", `⚠️ ${overdueCount}`));
-        } else {
-          // Only scheduled - show in accent color
-          ctx.ui.setStatus("today-todos", 
-            ctx.ui.theme.fg("accent", `📅 ${schedCount}`));
-        }
-      }
-    } catch (e) {
-      // Silently fail - today status is not critical
-    }
-  }
-
-  // Update status bars on session start
   pi.on("session_start", async (_event, ctx) => {
-    updateInboxStatus(ctx);
-    updateTodayStatus(ctx);
     setupTodoAutocomplete(ctx);
-    
-    // Set up periodic updates every 5 minutes
-    // Use unref() so the interval doesn't prevent process exit
-    const updateInterval = setInterval(() => {
-      updateInboxStatus(ctx);
-      updateTodayStatus(ctx);
-    }, 5 * 60 * 1000); // 5 minutes in milliseconds
-    updateInterval.unref();
-    
-    // Clean up interval on session end
-    (pi as any).on("session_end", async () => {
-      clearInterval(updateInterval);
-    });
   });
 }
 
dots/pi/agent/extensions/cost-tracker.ts
@@ -1,122 +1,49 @@
 /**
  * Cost Tracker Extension
  *
- * Shows session cost and token usage in the footer status bar,
- * similar to GitHub Copilot's premium request multiplier display.
+ * Shows total session cost and prompt-cache hit rate in the footer.
  */
 
 import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
 
-// Premium request multipliers (cost relative to Sonnet baseline)
-const MULTIPLIERS: Record<string, number> = {
-	// Anthropic
-	"claude-sonnet-4-20250514": 1,
-	"claude-sonnet-4-5-20250514": 1,
-	"claude-sonnet-4-5-20241022": 1,
-	"claude-haiku-3-5-20241022": 0.33,
-	"claude-opus-4-20250514": 3,
-	"claude-opus-4-5-20250120": 3,
-	// OpenAI
-	"gpt-4.1": 0,
-	"gpt-4o": 1,
-	"gpt-4o-mini": 0,
-	"o3": 3,
-	"o3-mini": 0.33,
-	"o4-mini": 0.33,
-	// Google
-	"gemini-2.5-pro": 1,
-	"gemini-2.5-flash": 0.33,
-	"gemini-2.0-flash": 0,
-};
-
-function getMultiplier(modelId: string): string {
-	for (const [pattern, mult] of Object.entries(MULTIPLIERS)) {
-		if (modelId.includes(pattern)) {
-			return `${mult}x`;
-		}
-	}
-	return "?x";
-}
-
 function formatCost(cost: number): string {
 	if (cost < 0.01) return `$${cost.toFixed(4)}`;
 	if (cost < 1) return `$${cost.toFixed(3)}`;
 	return `$${cost.toFixed(2)}`;
 }
 
-function formatTokens(n: number): string {
-	if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
-	if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
-	return `${n}`;
-}
-
 export default function (pi: ExtensionAPI) {
 	let totalCost = 0;
 	let totalInput = 0;
-	let totalOutput = 0;
 	let totalCacheRead = 0;
-	let currentModel = "";
+	let totalCacheWrite = 0;
 
 	function updateStatus(ctx: { ui: any }) {
-		const theme = ctx.ui.theme;
-		const mult = getMultiplier(currentModel);
-		const parts = [
-			theme.fg("dim", "cost:"),
-			theme.fg("accent", formatCost(totalCost)),
-			theme.fg("dim", `[${mult}]`),
-			theme.fg("dim", `in:${formatTokens(totalInput)}`),
-			theme.fg("dim", `out:${formatTokens(totalOutput)}`),
-		];
-		if (totalCacheRead > 0) {
-			parts.push(theme.fg("dim", `cache:${formatTokens(totalCacheRead)}`));
-		}
-		ctx.ui.setStatus("cost-tracker", parts.join(" "));
+		const totalPromptTokens = totalInput + totalCacheRead + totalCacheWrite;
+		const cacheHitPercent = totalPromptTokens === 0 ? 0 : Math.round((totalCacheRead / totalPromptTokens) * 100);
+		ctx.ui.setStatus("cost-tracker", ctx.ui.theme.fg("accent", `${formatCost(totalCost)} ↺${cacheHitPercent}%`));
 	}
 
-	pi.on("session_start", async (_event, ctx) => {
-		// Restore from existing session entries
-		for (const entry of ctx.sessionManager.getBranch()) {
-			if (entry.type === "message" && entry.message.role === "assistant") {
-				const msg = entry.message as any;
-				if (msg.usage) {
-					totalInput += msg.usage.input || 0;
-					totalOutput += msg.usage.output || 0;
-					totalCacheRead += msg.usage.cacheRead || 0;
-					if (msg.usage.cost) {
-						totalCost += msg.usage.cost.total || 0;
-					}
-				}
-				if (msg.model) currentModel = msg.model;
-			}
-		}
-		updateStatus(ctx);
-	});
-
-	pi.on("model_select", async (event, ctx) => {
-		currentModel = (event as any).modelId || "";
-		updateStatus(ctx);
-	});
-
-	pi.on("turn_end", async (_event, ctx) => {
-		// Recalculate from session to stay accurate
+	function recalculate(ctx: { sessionManager: any; ui: any }) {
 		totalCost = 0;
 		totalInput = 0;
-		totalOutput = 0;
 		totalCacheRead = 0;
+		totalCacheWrite = 0;
+
 		for (const entry of ctx.sessionManager.getBranch()) {
-			if (entry.type === "message" && entry.message.role === "assistant") {
-				const msg = entry.message as any;
-				if (msg.usage) {
-					totalInput += msg.usage.input || 0;
-					totalOutput += msg.usage.output || 0;
-					totalCacheRead += msg.usage.cacheRead || 0;
-					if (msg.usage.cost) {
-						totalCost += msg.usage.cost.total || 0;
-					}
-				}
-				if (msg.model) currentModel = msg.model;
-			}
+			if (entry.type !== "message" || entry.message.role !== "assistant") continue;
+
+			const usage = (entry.message as any).usage;
+			if (!usage) continue;
+
+			totalInput += usage.input || 0;
+			totalCacheRead += usage.cacheRead || 0;
+			totalCacheWrite += usage.cacheWrite || 0;
+			totalCost += usage.cost?.total || 0;
 		}
 		updateStatus(ctx);
-	});
+	}
+
+	pi.on("session_start", async (_event, ctx) => recalculate(ctx));
+	pi.on("turn_end", async (_event, ctx) => recalculate(ctx));
 }
dots/pi/agent/extensions/custom-footer.ts
@@ -18,6 +18,14 @@ import { hostname } from "node:os";
 import { execSync } from "node:child_process";
 import path from "node:path";
 
+const CONTEXT_WARNING_TOKENS = 150_000;
+const CACHE_COLD_CONTEXT_TOKENS = 50_000;
+// ponytail: provider cache TTLs differ; use provider-specific values if Pi exposes them.
+const CACHE_TTL_MS = 5 * 60_000;
+const PROVIDER_NAMES: Record<string, string> = {
+	"github-copilot": "gh", "google-vertex": "vx", "anthropic-vertex": "av", google: "g", "llama-cpp": "local",
+};
+
 // =============================================================================
 // Path Abbreviation
 // =============================================================================
@@ -173,8 +181,8 @@ function formatNumber(n: number): string {
 // =============================================================================
 
 function getProviderName(model: any): string {
-	// Use the actual provider from model config, not inferred from ID
-	return model?.provider || "unknown";
+	const provider = model?.provider || "unknown";
+	return PROVIDER_NAMES[provider] || provider;
 }
 
 // =============================================================================
@@ -227,29 +235,17 @@ function getModeText(modeName: string, hexColor: string | undefined, theme: any)
 // Context Usage
 // =============================================================================
 
-function getContextInfo(ctx: any, autoCompact: boolean): string | null {
+function getContextInfo(ctx: any, autoCompact: boolean, theme: any): string | null {
 	try {
 		const usage = ctx.getContextUsage?.();
 		if (!usage || !usage.contextWindow || usage.contextWindow === 0) return null;
-		
-		const percent = ((usage.tokens / usage.contextWindow) * 100).toFixed(1);
-		const compactStatus = autoCompact ? " (auto)" : "";
-		
-		return `${percent}%/${formatNumber(usage.contextWindow)}${compactStatus}`;
-	} catch {
-		return null;
-	}
-}
-
-// =============================================================================
-// Time
-// =============================================================================
-
-function getCurrentTime(): string {
-	const now = new Date();
-	const hours = String(now.getHours()).padStart(2, "0");
-	const minutes = String(now.getMinutes()).padStart(2, "0");
-	return `${hours}:${minutes}`;
+		const warnings: string[] = [];
+		if (usage.tokens >= CONTEXT_WARNING_TOKENS) warnings.push(theme.fg("warning", "⚠"));
+		const lastAssistant = [...ctx.sessionManager.getBranch()].reverse().find((entry: any) => entry.type === "message" && entry.message.role === "assistant");
+		const timestamp = lastAssistant?.message.timestamp ?? Date.parse(lastAssistant?.timestamp || "");
+		if (usage.tokens > CACHE_COLD_CONTEXT_TOKENS && Number.isFinite(timestamp) && Date.now() - timestamp > CACHE_TTL_MS) warnings.push(theme.fg("warning", "⚠cold"));
+		return `${((usage.tokens / usage.contextWindow) * 100).toFixed(1)}%/${formatNumber(usage.contextWindow)}${autoCompact ? " (auto)" : ""}${warnings.join("")}`;
+	} catch { return null; }
 }
 
 // =============================================================================
@@ -295,20 +291,18 @@ export default function (pi: ExtensionAPI) {
 				render(width: number): string[] {
 					try {
 					// Get all info
-					const time = getCurrentTime();
-					const host = hostname();
+					const host = process.env.SSH_CONNECTION ? hostname() : "";
 					const folder = abbreviatePath(ctx.cwd);
 					const git = getGitInfo();
 					const modelId = ctx.model?.id || "no-model";
 					const provider = getProviderName(ctx.model);
 					const modelName = getShortModelName(modelId);
 					const thinking = getThinkingInfo(pi);
-					const contextInfo = getContextInfo(ctx, autoCompactEnabled);
+					const contextInfo = getContextInfo(ctx, autoCompactEnabled, theme);
 
 					// Build components
-					const timeText = theme.fg("dim", time);
-					const hostIcon = theme.fg("accent", "🖥️");
-					const hostText = theme.fg("accent", host);
+					const hostIcon = host ? theme.fg("accent", "🖥️") : "";
+					const hostText = host ? theme.fg("accent", host) : "";
 					const folderText = theme.fg("dim", folder);
 					
 					const gitBranch = git.branch
@@ -341,13 +335,14 @@ export default function (pi: ExtensionAPI) {
 						.map(([, val]: [string, string]) => val);
 
 					// Adaptive footer: progressively drop components on narrow terminals
+					const hostSegment = host ? `${hostIcon} ${hostText}` : "";
 					const components = width < 60
-						? [timeText, modeText, contextText]
+						? [modeText, contextText]
 						: width < 80
-						? [timeText, folderText, gitBranch, modeText, providerModel, contextText]
+						? [folderText, gitBranch, modeText, providerModel, contextText]
 						: width < 100
-						? [timeText, `${hostIcon} ${hostText}`, folderText, gitBranch, modeText, providerModel, contextText]
-						: [timeText, `${hostIcon} ${hostText}`, folderText, gitBranch, modeText, providerModel, thinkingText, contextText, ...statusTexts];
+						? [hostSegment, folderText, gitBranch, modeText, providerModel, contextText]
+						: [hostSegment, folderText, gitBranch, modeText, providerModel, thinkingText, contextText, ...statusTexts];
 
 					const separator = theme.fg("dim", "  ");
 					const footer = components.filter(Boolean).join(separator);
@@ -385,20 +380,18 @@ export default function (pi: ExtensionAPI) {
 				render(width: number): string[] {
 					try {
 					// Get all info
-					const time = getCurrentTime();
-					const host = hostname();
+					const host = process.env.SSH_CONNECTION ? hostname() : "";
 					const folder = abbreviatePath(ctx.cwd);
 					const git = getGitInfo();
 					const modelId = ctx.model?.id || "no-model";
 					const provider = getProviderName(ctx.model);
 					const modelName = getShortModelName(modelId);
 					const thinking = getThinkingInfo(pi);
-					const contextInfo = getContextInfo(ctx, autoCompactEnabled);
+					const contextInfo = getContextInfo(ctx, autoCompactEnabled, theme);
 
 					// Build components
-					const timeText = theme.fg("dim", time);
-					const hostIcon = theme.fg("accent", "🖥️");
-					const hostText = theme.fg("accent", host);
+					const hostIcon = host ? theme.fg("accent", "🖥️") : "";
+					const hostText = host ? theme.fg("accent", host) : "";
 					const folderText = theme.fg("dim", folder);
 					
 					const gitBranch = git.branch
@@ -425,13 +418,14 @@ export default function (pi: ExtensionAPI) {
 						.filter(([key, val]: [string, string]) => key !== "mode" && key !== "mode-color" && Boolean(val))
 						.map(([, val]: [string, string]) => val);
 					// Adaptive footer: progressively drop components on narrow terminals
+					const hostSegment = host ? `${hostIcon} ${hostText}` : "";
 					const components = width < 60
-						? [timeText, modeText, contextText]
+						? [modeText, contextText]
 						: width < 80
-						? [timeText, folderText, gitBranch, modeText, providerModel, contextText]
+						? [folderText, gitBranch, modeText, providerModel, contextText]
 						: width < 100
-						? [timeText, `${hostIcon} ${hostText}`, folderText, gitBranch, modeText, providerModel, contextText]
-						: [timeText, `${hostIcon} ${hostText}`, folderText, gitBranch, modeText, providerModel, thinkingText, contextText, ...statusTexts];
+						? [hostSegment, folderText, gitBranch, modeText, providerModel, contextText]
+						: [hostSegment, folderText, gitBranch, modeText, providerModel, thinkingText, contextText, ...statusTexts];
 
 					const separator = theme.fg("dim", "  ");
 					const footer = components.filter(Boolean).join(separator);