Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/quota/src/ui.ts

Raw
import type {
	ExtensionContext,
	ThemeColor,
} from "@earendil-works/pi-coding-agent";
import type { ProviderQuota, QuotaBucket } from "./types.ts";

/** Best-effort presentation policy; provider adapters contain no footer priorities. */
export const FOOTER_LABELS: Readonly<Record<string, string>> = {
	anthropic: "5h",
	"openai-codex": "5h",
	"github-copilot": "Premium requests",
	minimax: "5h",
	"minimax-cn": "5h",
	zai: "5h",
	"zai-coding-cn": "5h",
	"kimi-coding": "5h",
	openrouter: "Free daily",
};

/**
 * Footer shows the account-wide allowance closest to exhaustion: any exhausted
 * window blocks use. Scoped limits and paid balances do not apply to every request.
 */
export function selectFooterBucket(
	quota: ProviderQuota,
): QuotaBucket | undefined {
	const preferred = FOOTER_LABELS[quota.provider];
	let binding: QuotaBucket | undefined;
	let bindingUsed = -1;
	for (const bucket of quota.buckets) {
		if (bucket.kind !== "allowance" || bucket.scope) continue;
		const used = usedPercent(bucket);
		if (used === undefined) continue;
		if (
			used > bindingUsed ||
			(used === bindingUsed && bucket.label === preferred)
		) {
			binding = bucket;
			bindingUsed = used;
		}
	}
	return (
		binding ??
		quota.buckets.find(
			(b) => b.label === preferred && b.value.state !== "unknown",
		) ??
		quota.buckets.find(
			(b) => b.kind === "allowance" && b.value.state === "measured",
		) ??
		quota.buckets.find((b) => b.value.state !== "unknown") ??
		quota.buckets[0]
	);
}

export function usedPercent(bucket: QuotaBucket): number | undefined {
	const v = bucket.value;
	if (v.state !== "measured") return undefined;
	if (v.usedPercent !== undefined) return v.usedPercent;
	if (v.total !== undefined && v.total > 0 && v.used !== undefined)
		return (v.used / v.total) * 100;
	if (v.total !== undefined && v.total > 0 && v.remaining !== undefined)
		return (1 - v.remaining / v.total) * 100;
	return undefined;
}

export function quotaColor(bucket: QuotaBucket): ThemeColor {
	const used = usedPercent(bucket);
	return used === undefined
		? "muted"
		: used < 50
			? "accent"
			: used < 80
				? "warning"
				: "error";
}

export function fmtReset(ts: number | undefined): string {
	if (ts === undefined || !Number.isFinite(ts)) return "";
	const diff = ts - Date.now();
	if (diff <= 0) return "";
	const d = Math.floor(diff / 86400000);
	const h = Math.floor((diff % 86400000) / 3600000);
	const m = Math.floor((diff % 3600000) / 60000);
	return d > 0 ? `${d}d${h}h${m}m` : h > 0 ? `${h}h${m}m` : `${m}m`;
}

function quantity(value: number): string {
	return value.toLocaleString("en-US", { maximumFractionDigits: 2 });
}

function valueText(bucket: QuotaBucket, compact: boolean): string {
	const v = bucket.value;
	if (v.state === "unknown") return "unknown";
	if (v.state === "unlimited") return "unlimited";
	const pct = usedPercent(bucket);
	const percentage =
		pct === undefined ? "" : `${Math.round(Math.min(100, Math.max(0, pct)))}%`;
	if (compact && percentage) return percentage;
	const named =
		v.unitLabel ??
		(v.unit === "unknown"
			? "units"
			: v.unit === "currency"
				? "currency units"
				: v.unit);
	// "Credits 12 credits left" repeats what the label already says.
	const stem = named.toLowerCase().replace(/s$/, "");
	const unit = bucketLabel(bucket).toLowerCase().includes(stem)
		? ""
		: ` ${named}`;
	if (v.unit === "percent")
		return percentage ? `${percentage} used` : "unknown";
	let amount =
		v.used !== undefined && v.total !== undefined
			? `${quantity(v.used)} / ${quantity(v.total)}${unit} used`
			: v.remaining !== undefined
				? `${quantity(v.remaining)}${unit} left`
				: v.used !== undefined
					? `${quantity(v.used)}${unit} used`
					: v.total !== undefined
						? `${quantity(v.total)}${unit} total`
						: "unknown";
	if (percentage && !compact) amount += ` (${percentage})`;
	return amount;
}

function bucketLabel(bucket: QuotaBucket): string {
	const period = bucket.period?.label;
	const title =
		period && period !== bucket.label
			? `${bucket.label} (${period})`
			: bucket.label;
	return bucket.scope ? `${title} · ${bucket.scope}` : title;
}

export function segmentText(
	quota: ProviderQuota,
	isActive: boolean,
): [string, string, string] {
	const bucket = selectFooterBucket(quota);
	if (!bucket) return ["", "", ""];
	const text = `${bucketLabel(bucket)} ${valueText(bucket, true)}`;
	const reset = fmtReset(bucket.period?.resetsAt);
	const prefix = isActive ? "" : `${quota.name} `;
	return [
		`${prefix}${text}${reset ? ` (${reset})` : ""}`,
		`${prefix}${text}`,
		text,
	];
}

export function quotaStatusLabel(
	quotas: readonly ProviderQuota[],
): string | undefined {
	const rows = quotas
		.filter((q) => q.buckets.length)
		.map((q) => segmentText(q, false)[0]);
	return rows.length ? rows.join(" · ") : undefined;
}

export function quotaPlainLabel(
	quotas: readonly ProviderQuota[],
): string | undefined {
	const rows: string[] = [];
	for (const quota of quotas) {
		const bucket = selectFooterBucket(quota);
		if (!bucket) continue;
		const reset = fmtReset(bucket.period?.resetsAt);
		rows.push(
			`${quota.name} quota ${bucketLabel(bucket)} ${valueText(bucket, false)}${reset ? `, resets in ${reset}` : ""}`,
		);
	}
	return rows.length ? rows.join("; ") : undefined;
}

export function widgetLines(
	quotas: readonly ProviderQuota[],
	theme: Pick<ExtensionContext["ui"]["theme"], "fg" | "bold">,
): string[] {
	const lines: string[] = [];
	for (const quota of quotas) {
		if (!quota.buckets.length) continue;
		lines.push(theme.bold(theme.fg("accent", `● ${quota.name}`)));
		// Code points approximate terminal width; provider labels are short and sanitized.
		const width = (text: string) => [...text].length;
		const labelWidth = Math.max(
			...quota.buckets.map((bucket) => width(bucketLabel(bucket))),
		);
		for (const bucket of quota.buckets) {
			const name = bucketLabel(bucket);
			const padded = name + " ".repeat(labelWidth - width(name));
			const used = usedPercent(bucket);
			const filled =
				used === undefined
					? 0
					: Math.round((Math.min(100, Math.max(0, used)) / 100) * 12);
			const bar =
				used === undefined
					? ""
					: `${"█".repeat(filled)}${"░".repeat(12 - filled)} `;
			const reset = fmtReset(bucket.period?.resetsAt);
			const time = reset ? ` · resets in ${reset}` : "";
			lines.push(
				`  ${padded}  ${theme.fg(quotaColor(bucket), `${bar}${valueText(bucket, false)}`)}${theme.fg("dim", time)}`,
			);
		}
		const age = Math.max(0, Math.round((Date.now() - quota.observedAt) / 1000));
		lines.push(
			theme.fg(
				"dim",
				`  ↻ observed ${age < 60 ? `${age}s` : `${Math.round(age / 60)}m`} ago`,
			),
		);
	}
	return lines.length ? lines : [theme.fg("dim", "  Quota unavailable")];
}