pi-hud-plus 0.2.0 → 0.3.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.
package/src/i18n/en.ts CHANGED
@@ -3,6 +3,9 @@ import type { Messages } from "./types.ts";
3
3
  export const en: Messages = {
4
4
  // Labels
5
5
  "label.context": "Context",
6
+ "label.usage": "Usage",
7
+ "label.weekly": "Weekly",
8
+ "label.monthly": "Monthly",
6
9
  "label.approxRam": "Approx RAM",
7
10
  "label.promptCache": "Cache",
8
11
  "label.estimatedCost": "Est.",
@@ -15,8 +18,11 @@ export const en: Messages = {
15
18
 
16
19
  // Status
17
20
  "status.expired": "expired",
21
+ "status.limitReached": "Limit reached",
18
22
 
19
23
  // Format
24
+ "format.resets": "resets",
25
+ "format.resetsIn": "resets in",
20
26
  "format.at": "at",
21
27
  "format.in": "in",
22
28
  "format.cache": "cache",
package/src/i18n/types.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  export type MessageKey =
2
2
  // Labels
3
3
  | "label.context"
4
+ | "label.usage"
5
+ | "label.weekly"
6
+ | "label.monthly"
4
7
  | "label.approxRam"
5
8
  | "label.promptCache"
6
9
  | "label.estimatedCost"
@@ -12,7 +15,10 @@ export type MessageKey =
12
15
  | "label.prompts"
13
16
  // Status
14
17
  | "status.expired"
18
+ | "status.limitReached"
15
19
  // Format
20
+ | "format.resets"
21
+ | "format.resetsIn"
16
22
  | "format.at"
17
23
  | "format.in"
18
24
  | "format.cache"
@@ -3,6 +3,9 @@ import type { Messages } from "./types.ts";
3
3
  export const zhHans: Messages = {
4
4
  // Labels
5
5
  "label.context": "上下文",
6
+ "label.usage": "用量",
7
+ "label.weekly": "本周",
8
+ "label.monthly": "本月",
6
9
  "label.approxRam": "内存",
7
10
  "label.promptCache": "缓存",
8
11
  "label.estimatedCost": "估算",
@@ -15,8 +18,11 @@ export const zhHans: Messages = {
15
18
 
16
19
  // Status
17
20
  "status.expired": "已过期",
21
+ "status.limitReached": "已达上限",
18
22
 
19
23
  // Format
24
+ "format.resets": "重置于",
25
+ "format.resetsIn": "重置剩余",
20
26
  "format.at": "",
21
27
  "format.in": "输入",
22
28
  "format.cache": "缓存",
package/src/index.ts CHANGED
@@ -14,13 +14,15 @@ import {
14
14
  import { hasTickingElement, startClock } from "./clock.ts";
15
15
  import { registerCommands } from "./commands.ts";
16
16
  import { loadConfig, type HudConfig } from "./config.ts";
17
+ import { getUsageFromExternalSnapshot } from "./external-usage.ts";
17
18
  import { runExtraCmd } from "./extra-cmd.ts";
18
- import { getGitStatus } from "./git.ts";
19
+ import { getGitStatus, type GitStatusOptions } from "./git.ts";
19
20
  import { getMemoryUsage } from "./memory.ts";
20
21
  import { renderHud } from "./render/index.ts";
21
22
  import { createSessionReader } from "./session.ts";
22
- import { createSpeedTracker } from "./speed-tracker.ts";
23
- import type { HudContext, HudEnvironment, HudSnapshot, HudTool } from "./types.ts";
23
+ import { createSpeedTracker, SPEED_WINDOW_MS } from "./speed-tracker.ts";
24
+ import type { HudContext, HudEnvironment, HudSnapshot, HudTool, UsageLimit } from "./types.ts";
25
+ import { codex, detectVendor, parseCodexRateLimits, type UsageModel } from "./usage-vendors.ts";
24
26
 
25
27
  interface Session {
26
28
  generation: number;
@@ -31,8 +33,12 @@ interface Session {
31
33
  displacedNotice?: ReturnType<typeof setTimeout>;
32
34
  stopClock?: () => void;
33
35
  trackSpeed: ReturnType<typeof createSpeedTracker>;
36
+ /** Hides the speed once its reading is stale. */
37
+ speedExpiry?: ReturnType<typeof setTimeout>;
34
38
  git?: BackgroundJob;
35
39
  extra?: BackgroundJob;
40
+ /** Absent when showUsage is off. */
41
+ usage?: UsageJob;
36
42
  footerData?: ReadonlyFooterDataProvider;
37
43
  /** Context from the streaming reply's usage; wins over getContextUsage() until a clearing event. */
38
44
  liveContext?: HudContext;
@@ -97,6 +103,19 @@ interface BackgroundJob {
97
103
  const GIT_THROTTLE_MS = 2000;
98
104
  const GIT_BACKSTOP_MS = 30_000;
99
105
  const EXTRA_BACKSTOP_MS = 30_000;
106
+ /** A fetch is skipped while the current vendor's data is younger than this. */
107
+ const USAGE_SKIP_MS = 60_000;
108
+ const USAGE_BACKSTOP_MS = 5 * 60_000;
109
+
110
+ /** The usage job: the current vendor's Usage limit, else the External usage snapshot. */
111
+ interface UsageJob extends BackgroundJob {
112
+ /** The model changed; another vendor clears the shown data until its own arrives. */
113
+ selectModel(model: UsageModel): void;
114
+ /** A provider stream frame; Codex's codex.rate_limits carries its Usage limit. */
115
+ frame(data: unknown): void;
116
+ /** Re-shows the data, re-reading the External usage snapshot (for freshness) while there's no native data. */
117
+ show(): void;
118
+ }
100
119
 
101
120
  // On globalThis, not module scope: /reload re-imports this module, and the notice must fire once per pi process.
102
121
  const NOTICE_SHOWN = Symbol.for("pi-hud-plus.displacedNoticeShown");
@@ -145,7 +164,7 @@ export default function piHud(pi: ExtensionAPI): void {
145
164
  const readSession = createSessionReader();
146
165
 
147
166
  /** Async git refresh: at most one run in flight, triggers coalesced, runs spaced by the throttle, plus a backstop. */
148
- const startGitJob = (gen: number, cwd: string, footerData: ReadonlyFooterDataProvider, options: HudConfig["gitStatus"]): BackgroundJob => {
167
+ const startGitJob = (gen: number, cwd: string, footerData: ReadonlyFooterDataProvider, options: GitStatusOptions): BackgroundJob => {
149
168
  let inFlight = false;
150
169
  let pending = false;
151
170
  let lastRun = -Infinity;
@@ -215,6 +234,77 @@ export default function piHud(pi: ExtensionAPI): void {
215
234
  return { trigger: () => void run(), stop: () => clearInterval(backstop) };
216
235
  };
217
236
 
237
+ /** Usage refresh: on trigger and a backstop, at most one fetch in flight, skipped while the data is fresh. Never from render. */
238
+ const startUsageJob = (
239
+ gen: number,
240
+ config: HudConfig,
241
+ model: UsageModel | undefined,
242
+ registry: ExtensionContext["modelRegistry"],
243
+ onShown: () => void,
244
+ ): UsageJob => {
245
+ let vendor = detectVendor(model);
246
+ let native: UsageLimit | null = null;
247
+ // The last fetch attempt (success or failure) or frame: a vendor that's down gets at most one request per USAGE_SKIP_MS.
248
+ let freshAt = -Infinity;
249
+ // Bumped on a vendor switch or a frame: an in-flight fetch is then ignored (it predates the data) and doesn't block a new one.
250
+ let epoch = 0;
251
+ let inFlight: number | undefined;
252
+
253
+ const show = () => {
254
+ if (!isLive(gen)) return;
255
+ const usageLimit = native ?? getUsageFromExternalSnapshot(config);
256
+ if (JSON.stringify(usageLimit) !== JSON.stringify(session!.snapshot.usageLimit ?? null)) update(gen, { usageLimit });
257
+ onShown();
258
+ };
259
+ const setNative = (usage: UsageLimit | null) => {
260
+ native = usage;
261
+ show();
262
+ };
263
+
264
+ const run = async () => {
265
+ show();
266
+ if (!isLive(gen) || !vendor || !model || inFlight === epoch || Date.now() - freshAt < USAGE_SKIP_MS) return;
267
+ const mine = (inFlight = epoch);
268
+ freshAt = Date.now();
269
+ const [current, forModel] = [vendor, model];
270
+ const usage = await registry
271
+ .getApiKeyAndHeaders(forModel)
272
+ .then((auth) => (auth.ok && auth.apiKey ? current.fetch(forModel, auth.apiKey) : null))
273
+ .catch(() => null);
274
+ if (inFlight === mine) inFlight = undefined;
275
+ if (mine === epoch && isLive(gen)) setNative(usage);
276
+ };
277
+
278
+ const backstop = setInterval(() => void run(), USAGE_BACKSTOP_MS);
279
+ backstop.unref?.();
280
+ void run();
281
+ return {
282
+ trigger: () => void run(),
283
+ stop: () => clearInterval(backstop),
284
+ show,
285
+ selectModel(next) {
286
+ const nextVendor = detectVendor(next);
287
+ // Another baseUrl host is another account (GLM's open.bigmodel.cn vs api.z.ai), so its data is another's too.
288
+ const switched = nextVendor !== vendor || URL.parse(next.baseUrl)?.hostname !== URL.parse(model?.baseUrl ?? "")?.hostname;
289
+ model = next;
290
+ if (switched) {
291
+ vendor = nextVendor;
292
+ epoch++;
293
+ native = null;
294
+ freshAt = -Infinity;
295
+ }
296
+ void run();
297
+ },
298
+ frame(data) {
299
+ const usage = vendor === codex ? parseCodexRateLimits(data) : null;
300
+ if (!usage || !isLive(gen)) return;
301
+ epoch++;
302
+ freshAt = Date.now();
303
+ setNative(usage);
304
+ },
305
+ };
306
+ };
307
+
218
308
  pi.on("session_start", (_event, ctx: ExtensionContext) => {
219
309
  if (!ctx.hasUI || ctx.mode !== "tui") return;
220
310
  const config = loadConfig(getAgentDir());
@@ -240,18 +330,31 @@ export default function piHud(pi: ExtensionAPI): void {
240
330
  tools: new Map(),
241
331
  breakdown,
242
332
  });
243
- if (hasTickingElement(config)) {
244
- current.stopClock = startClock((now) => {
245
- update(current.generation, { now });
246
- // Memory is sampled here, never in render; the first reading lands on the first tick.
247
- if (config.display.showMemoryUsage) void getMemoryUsage().then((memory) => update(current.generation, { memory }));
248
- });
249
- }
333
+ const tick = (now: number) => {
334
+ update(current.generation, { now });
335
+ current.usage?.show();
336
+ // Memory is sampled here, never in render; the first reading lands on the first tick.
337
+ if (config.display.showMemoryUsage) void getMemoryUsage().then((memory) => update(current.generation, { memory }));
338
+ };
339
+ // A shown Limit window's reset countdown ticks too; a Balance hides the windows, so it doesn't.
340
+ const syncClock = () => {
341
+ const u = current.snapshot.usageLimit;
342
+ const counting = !!u && !u.balanceLabel && !!(u.fiveHourResetAt || u.sevenDayResetAt || u.monthlyResetAt);
343
+ const wanted = hasTickingElement(config) || counting;
344
+ if (!isLive(current.generation) || wanted === !!current.stopClock) return;
345
+ if (wanted) current.stopClock = startClock(tick);
346
+ else {
347
+ current.stopClock!();
348
+ current.stopClock = undefined;
349
+ }
350
+ };
351
+ if (config.display.showUsage) current.usage = startUsageJob(current.generation, config, ctx.model, ctx.modelRegistry, syncClock);
352
+ syncClock();
250
353
  setFooter(ctx.ui, (tui, _theme, footerData) => {
251
354
  current.requestRender = () => tui.requestRender();
252
355
  current.footerData = footerData;
253
356
  current.snapshot = { ...current.snapshot, model: modelInfo(ctx.model, footerData) };
254
- if (config.gitStatus.enabled) current.git = startGitJob(current.generation, ctx.cwd, footerData, config.gitStatus);
357
+ if (config.gitStatus.enabled) current.git = startGitJob(current.generation, ctx.cwd, footerData, { ...config.gitStatus, linkBranch: config.lineLayout === "expanded" });
255
358
  return {
256
359
  // Statuses are read live: pi requests a render whenever an extension sets one.
257
360
  render: (width) => renderHud({ ...current.snapshot, extensionStatuses: footerData.getExtensionStatuses() }, config, width),
@@ -262,6 +365,7 @@ export default function piHud(pi: ExtensionAPI): void {
262
365
  current.stopClock?.();
263
366
  current.git?.stop();
264
367
  current.extra?.stop();
368
+ current.usage?.stop();
265
369
  current.displacedNotice = setTimeout(() => {
266
370
  if (globals[NOTICE_SHOWN]) return;
267
371
  globals[NOTICE_SHOWN] = true;
@@ -278,13 +382,19 @@ export default function piHud(pi: ExtensionAPI): void {
278
382
  // Session data: after these events the session's entries or name may have changed.
279
383
  const refreshSession = (ctx: ExtensionContext) => update(generation, { session: readSession(pi, ctx), now: Date.now() });
280
384
 
281
- // Speed: sampled from the streaming reply. Most updates come too close together for a reading; keep showing the last one.
385
+ // Speed: sampled from the streaming reply. Most updates come too close together for a reading; keep showing the last one
386
+ // until it's stale, as claude-hud hides the speed once a reply stalls past the window.
282
387
  const sampleSpeed = (s: Session, usage: Usage) => {
283
388
  const speed = s.trackSpeed(usage.output, Date.now());
284
- if (speed !== null) update(generation, { speed });
389
+ if (speed === null) return;
390
+ update(generation, { speed });
391
+ clearTimeout(s.speedExpiry);
392
+ s.speedExpiry = setTimeout(() => live() === s && clearSpeed(s), SPEED_WINDOW_MS);
393
+ s.speedExpiry.unref?.();
285
394
  };
286
395
  // The reply stopped streaming: no fresh reading, so claude-hud would hide the speed.
287
396
  const clearSpeed = (s: Session) => {
397
+ clearTimeout(s.speedExpiry);
288
398
  if (s.snapshot.speed !== undefined) update(generation, { speed: undefined });
289
399
  };
290
400
 
@@ -341,7 +451,9 @@ export default function piHud(pi: ExtensionAPI): void {
341
451
  session: readSession(pi, ctx, event.model),
342
452
  });
343
453
  clearLiveContext(s, ctx);
454
+ s.usage?.selectModel(event.model);
344
455
  });
456
+ pi.on("provider_stream_event", (event) => live()?.usage?.frame(event.data));
345
457
  // The run's system prompt options are what the agent actually loaded.
346
458
  pi.on("before_agent_start", (event) => {
347
459
  if (!live()?.snapshot.environment) return;
@@ -390,6 +502,7 @@ export default function piHud(pi: ExtensionAPI): void {
390
502
  clearSpeed(s);
391
503
  s.git?.trigger();
392
504
  s.extra?.trigger();
505
+ s.usage?.trigger();
393
506
  clearLiveContext(s, ctx);
394
507
  });
395
508
  pi.on("session_info_changed", (_event, ctx) => {
@@ -407,11 +520,13 @@ export default function piHud(pi: ExtensionAPI): void {
407
520
 
408
521
  pi.on("session_shutdown", (_event, ctx) => {
409
522
  if (!session) return;
410
- const { displaced, displacedNotice, stopClock } = session;
523
+ const { displaced, displacedNotice, speedExpiry, stopClock } = session;
411
524
  clearTimeout(displacedNotice);
525
+ clearTimeout(speedExpiry);
412
526
  stopClock?.();
413
527
  session.git?.stop();
414
528
  session.extra?.stop();
529
+ session.usage?.stop();
415
530
  session = undefined;
416
531
  generation++;
417
532
  // Only while we still own the footer: otherwise this would wipe the other extension's footer.
@@ -133,11 +133,10 @@ export function getContextColor(
133
133
  return resolveAnsi(colors?.context, GREEN);
134
134
  }
135
135
 
136
- /** claude-hud's quota colours; the usage overrides are gone, so only critical is configurable. */
137
136
  export function getQuotaColor(percent: number, colors?: Partial<HudColorOverrides>): string {
138
137
  if (percent >= 90) return resolveAnsi(colors?.critical, RED);
139
- if (percent >= 75) return BRIGHT_MAGENTA;
140
- return BRIGHT_BLUE;
138
+ if (percent >= 75) return resolveAnsi(colors?.usageWarning, BRIGHT_MAGENTA);
139
+ return resolveAnsi(colors?.usage, BRIGHT_BLUE);
141
140
  }
142
141
 
143
142
  export function quotaBar(percent: number, width: number = 10, colors?: Partial<HudColorOverrides>): string {
@@ -0,0 +1,50 @@
1
+ import type { TimeFormatMode } from "../config.ts";
2
+ import { t } from "../i18n/index.ts";
3
+
4
+ /**
5
+ * claude-hud's reset time for a Limit window, against `now` (the snapshot's clock) instead of `new Date()`.
6
+ * relative `2h 30m`, absolute `at 14:30` (date added on another day), anything else both: `2h 30m, at 14:30`.
7
+ * Empty when the reset is unknown or past.
8
+ */
9
+ export function formatResetTime(resetAt: Date | null, mode: TimeFormatMode = "relative", now: number = Date.now()): string {
10
+ if (!resetAt) return "";
11
+
12
+ const diffMs = resetAt.getTime() - now;
13
+ if (diffMs <= 0) return "";
14
+
15
+ if (mode === "relative") return formatRelative(diffMs);
16
+
17
+ const absolute = formatAbsolute(resetAt, new Date(now));
18
+ if (mode === "absolute") return absolute;
19
+
20
+ // A comma, not parentheses: callers wrap the result in their own (...).
21
+ return `${formatRelative(diffMs)}, ${absolute}`;
22
+ }
23
+
24
+ function formatRelative(diffMs: number): string {
25
+ const diffMins = Math.ceil(diffMs / 60000);
26
+ if (diffMins < 60) return `${diffMins}m`;
27
+
28
+ const hours = Math.floor(diffMins / 60);
29
+ const mins = diffMins % 60;
30
+
31
+ if (hours >= 24) {
32
+ const days = Math.floor(hours / 24);
33
+ const remHours = hours % 24;
34
+ return remHours > 0 ? `${days}d ${remHours}h` : `${days}d`;
35
+ }
36
+
37
+ return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
38
+ }
39
+
40
+ function formatAbsolute(resetAt: Date, now: Date): string {
41
+ // Locales that bake the preposition into format.resets (zh: 重置于) set format.at to "".
42
+ const at = t("format.at");
43
+ const prefix = at ? `${at} ` : "";
44
+ const timeStr = resetAt.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
45
+
46
+ if (resetAt.toDateString() === now.toDateString()) return `${prefix}${timeStr}`;
47
+
48
+ const dateStr = resetAt.toLocaleDateString([], { month: "short", day: "numeric" });
49
+ return `${prefix}${dateStr} ${timeStr}`;
50
+ }
@@ -5,6 +5,7 @@ import type { HudSnapshot, RenderContext } from "../types.ts";
5
5
  import { dim } from "./colors.ts";
6
6
  import { renderEnvironmentLine } from "./lines/environment.ts";
7
7
  import { renderContextLine } from "./lines/context.ts";
8
+ import { renderGitFilesLine } from "./lines/git.ts";
8
9
  import { renderMemoryLine } from "./lines/memory.ts";
9
10
  import { renderPromptCacheLine } from "./lines/prompt-cache.ts";
10
11
  import { renderProjectLine } from "./lines/project.ts";
@@ -12,12 +13,14 @@ import { renderSessionTimeLine } from "./lines/session-time.ts";
12
13
  import { renderSessionTokensLine } from "./lines/session-stats.ts";
13
14
  import { renderSessionLine } from "./session-line.ts";
14
15
  import { renderToolsLine } from "./tools-line.ts";
16
+ import { renderUsageLine } from "./lines/usage.ts";
15
17
 
16
18
 
17
19
  /** One Line module per Element. */
18
20
  const ELEMENT_RENDERERS: Record<HudElement, (ctx: RenderContext) => string | null> = {
19
21
  project: renderProjectLine,
20
22
  context: renderContextLine,
23
+ usage: renderUsageLine,
21
24
  promptCache: renderPromptCacheLine,
22
25
  memory: renderMemoryLine,
23
26
  environment: renderEnvironmentLine,
@@ -112,7 +115,9 @@ function renderExpanded(ctx: RenderContext): Array<{ line: string; isActivity: b
112
115
  lines.push({ line, isActivity: ACTIVITY_ELEMENTS.has(element) });
113
116
  }
114
117
 
115
- // claude-hud's git files Line goes here, always last.
118
+ // Last of the Element Lines, as in claude-hud; the token and extension status Lines still follow.
119
+ const gitFilesLine = renderGitFilesLine(ctx);
120
+ if (gitFilesLine) lines.push({ line: gitFilesLine, isActivity: false });
116
121
  return lines;
117
122
  }
118
123
 
@@ -1,8 +1,11 @@
1
1
  // Ported from claude-hud: the gitPart of render/lines/project.ts (expanded) and render/session-line.ts (compact).
2
- // branchUrl hyperlinking is not ported.
2
+ // renderGitFilesLine and the branch link are ported from project.ts.
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
3
5
  import type { HudConfig } from "../../config.ts";
6
+ import type { LineDiff } from "../../git.ts";
4
7
  import type { RenderContext } from "../../types.ts";
5
- import { git as gitColor, gitBranch as gitBranchColor, warning as warningColor, critical as criticalColor, red, green } from "../colors.ts";
8
+ import { git as gitColor, gitBranch as gitBranchColor, warning as warningColor, critical as criticalColor, red, green, yellow, dim } from "../colors.ts";
6
9
  import { sanitize } from "../../sanitize.ts";
7
10
 
8
11
  /** The project Line's `git:(branch* ↑1 ↓2 [+3 -4])` segment, or null when git is off or there is no status. */
@@ -13,20 +16,16 @@ export function renderGitPart({ snapshot, config }: RenderContext): string | nul
13
16
  if (!gitConfig.enabled || !status) return null;
14
17
 
15
18
  const branchText = sanitize(status.branch + (gitConfig.showDirty && status.isDirty ? "*" : ""));
16
- const gitInner: string[] = [gitBranchColor(branchText, colors)];
19
+ const branchUrl = status.githubUrl && `${status.githubUrl}/tree/${encodeURIComponent(status.branch)}`;
20
+ const gitInner: string[] = [safeHyperlink(branchUrl, gitBranchColor(branchText, colors))];
17
21
 
18
22
  if (gitConfig.showAheadBehind) {
19
23
  if (status.ahead > 0) gitInner.push(formatAheadCount(status.ahead, gitConfig, colors));
20
24
  if (status.behind > 0) gitInner.push(gitBranchColor(`↓${status.behind}`, colors));
21
25
  }
22
26
 
23
- if (gitConfig.showFileStats && status.lineDiff) {
24
- const { added, deleted } = status.lineDiff;
25
- const diffParts: string[] = [];
26
- if (added > 0) diffParts.push(green(`+${added}`));
27
- if (deleted > 0) diffParts.push(red(`-${deleted}`));
28
- if (diffParts.length > 0) gitInner.push(`[${diffParts.join(" ")}]`);
29
- }
27
+ const diffParts = gitConfig.showFileStats ? lineDiffParts(status.lineDiff) : "";
28
+ if (diffParts) gitInner.push(`[${diffParts}]`);
30
29
 
31
30
  return `${gitColor("git:(", colors)}${gitInner.join(" ")}${gitColor(")", colors)}`;
32
31
  }
@@ -56,12 +55,56 @@ export function renderCompactGitPart({ snapshot, config }: RenderContext): strin
56
55
  return `${gitColor("git:(", config.colors)}${gitBranchColor(sanitize(gitParts.join("")), config.colors)}${gitColor(")", config.colors)}`;
57
56
  }
58
57
 
58
+ /** The git files Line: up to 6 changed files, newest first, each linked (OSC 8) when inside cwd. Expanded layout only. */
59
+ export function renderGitFilesLine({ snapshot, config, width }: RenderContext): string | null {
60
+ const fileStats = snapshot.git?.fileStats;
61
+ if (!config.gitStatus.enabled || !config.gitStatus.showFileStats || !fileStats || width < 60) return null;
62
+ const { trackedFiles, untracked } = fileStats;
63
+ if (trackedFiles.length === 0 && untracked === 0) return null;
64
+
65
+ const parts = trackedFiles.slice(0, 6).map((file) => {
66
+ const color = file.type === "added" ? green : file.type === "deleted" ? red : yellow;
67
+ const prefix = file.type === "added" ? "+" : file.type === "deleted" ? "-" : "~";
68
+ const name = color(sanitize(file.basename));
69
+ const resolved = path.resolve(fileStats.root ?? snapshot.cwd, file.fullPath);
70
+ const relative = path.relative(snapshot.cwd, resolved);
71
+ const inCwd = relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
72
+ const diffParts = lineDiffParts(file.lineDiff);
73
+ return color(prefix) + (inCwd ? safeHyperlink(pathToFileURL(resolved).href, name) : name) + (diffParts ? dim(`(${diffParts})`) : "");
74
+ });
75
+
76
+ if (trackedFiles.length > 6) parts.push(dim(`+${trackedFiles.length - 6} more`));
77
+ if (untracked > 0) parts.push(dim(`?${untracked}`));
78
+ return parts.join(" ");
79
+ }
80
+
59
81
  /** Project and git as Line parts: one part (`project git:(…)`), or two when `branchOverflow` is "wrap". */
60
82
  export function withGit(project: string | null, git: string | null, config: HudConfig): string[] {
61
83
  if (project && git && config.gitStatus.branchOverflow === "truncate") return [`${project} ${git}`];
62
84
  return [project, git].filter((part) => part !== null);
63
85
  }
64
86
 
87
+ /** `+3 -4` in green and red, skipping zeros; "" when there's nothing to show. */
88
+ function lineDiffParts(diff: LineDiff | undefined): string {
89
+ if (!diff) return "";
90
+ const parts: string[] = [];
91
+ if (diff.added > 0) parts.push(green(`+${diff.added}`));
92
+ if (diff.deleted > 0) parts.push(red(`-${diff.deleted}`));
93
+ return parts.join(" ");
94
+ }
95
+
96
+ /** OSC 8 link, or the plain text when the URI isn't a valid https/file URL. URL parsing percent-encodes control characters. */
97
+ function safeHyperlink(uri: string | undefined, text: string): string {
98
+ if (!uri) return text;
99
+ try {
100
+ const parsed = new URL(sanitize(uri));
101
+ if (parsed.protocol !== "https:" && parsed.protocol !== "file:") return text;
102
+ return `\x1b]8;;${parsed}\x1b\\${text}\x1b]8;;\x1b\\`;
103
+ } catch {
104
+ return text;
105
+ }
106
+ }
107
+
65
108
  function formatAheadCount(ahead: number, gitConfig: HudConfig["gitStatus"], colors: HudConfig["colors"]): string {
66
109
  const value = `↑${ahead}`;
67
110
  if (gitConfig.pushCriticalThreshold > 0 && ahead >= gitConfig.pushCriticalThreshold) return criticalColor(value, colors);