forked from nicobailon/pi-powerline-footer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegments.ts
More file actions
543 lines (464 loc) · 18.7 KB
/
Copy pathsegments.ts
File metadata and controls
543 lines (464 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import { hostname as osHostname } from "node:os";
import { basename } from "node:path";
import { visibleWidth } from "@earendil-works/pi-tui";
import type { BuiltinStatusLineSegmentId, RenderedSegment, SegmentContext, SemanticColor, StatusLineSegment, StatusLineSegmentId } from "./types.ts";
import { normalizeCompactExtensionStatus, normalizeExtensionStatusValue } from "./powerline-config.ts";
import { fg, rainbow, applyColor } from "./theme.ts";
import { getIcons, SEP_DOT, getThinkingText } from "./icons.ts";
import type { IconSet } from "./icons.ts";
import { getGitRemoteHost } from "./git-status.ts";
import type { GitHost } from "./git-status.ts";
import { formatSubscriptionUsageSummary } from "./subscription-usage.ts";
function color(ctx: SegmentContext, semantic: SemanticColor, text: string): string {
return fg(ctx.theme, semantic, text, ctx.colors);
}
// ═══════════════════════════════════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════════════════════════════════
function withIcon(icon: string, text: string): string {
return icon ? `${icon} ${text}` : text;
}
function formatTokens(n: number): string {
if (n < 1000) return n.toString();
if (n < 10000) return `${(n / 1000).toFixed(1)}k`;
if (n < 1000000) return `${Math.round(n / 1000)}k`;
if (n < 10000000) return `${(n / 1000000).toFixed(1)}M`;
return `${Math.round(n / 1000000)}M`;
}
function formatDuration(ms: number): string {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) return `${hours}h${minutes % 60}m`;
if (minutes > 0) return `${minutes}m${seconds % 60}s`;
return `${seconds}s`;
}
// ═══════════════════════════════════════════════════════════════════════════
// Segment Implementations
// ═══════════════════════════════════════════════════════════════════════════
const modelSegment: StatusLineSegment = {
id: "model",
render(ctx) {
const icons = getIcons();
const opts = ctx.options.model ?? {};
let modelName = ctx.model?.name || ctx.model?.id || "no-model";
const provider = ctx.model?.provider || ctx.model?.providerId || ctx.model?.providerName || "";
if (opts.display === "qualified" && ctx.model?.id) {
modelName = provider && !ctx.model.id.includes("/") ? `${provider}/${ctx.model.id}` : ctx.model.id;
} else if (modelName.startsWith("Claude ")) {
modelName = modelName.slice(7);
}
let content = withIcon(icons.model, modelName);
if (opts.display === undefined && provider && !modelName.startsWith(`${provider}/`)) {
content += ` (${provider})`;
}
if (opts.showThinkingLevel !== false && ctx.model?.reasoning) {
const level = ctx.thinkingLevel || "off";
if (level !== "off") {
const thinkingText = getThinkingText(level);
if (thinkingText) {
content += `${SEP_DOT}${thinkingText}`;
}
}
}
return { content: color(ctx, "model", content), visible: true };
},
};
const shellModeSegment: StatusLineSegment = {
id: "shell_mode",
render(ctx) {
if (!ctx.shellModeActive) {
return { content: "", visible: false };
}
const shellName = ctx.shellName ?? "shell";
const state = ctx.shellRunning ? "run" : "idle";
const cwd = ctx.shellCwd ? basename(ctx.shellCwd) : null;
const parts = [shellName, state];
if (cwd) {
parts.push(cwd);
}
return { content: color(ctx, "shellMode", parts.join(SEP_DOT)), visible: true };
},
};
const pathSegment: StatusLineSegment = {
id: "path",
render(ctx) {
const icons = getIcons();
const opts = ctx.options.path ?? {};
const mode = opts.mode ?? "basename";
let pwd = ctx.shellModeActive && ctx.shellCwd ? ctx.shellCwd : (ctx.cwd ?? process.cwd());
const home = process.env.HOME || process.env.USERPROFILE;
if (mode === "basename") {
// Just the last directory component (cross-platform)
pwd = basename(pwd) || pwd;
} else {
// Abbreviate home directory for abbreviated/full modes
if (home && pwd.startsWith(home)) {
pwd = `~${pwd.slice(home.length)}`;
}
// Strip /work/ prefix (common in containers)
if (pwd.startsWith("/work/")) {
pwd = pwd.slice(6);
}
// Truncate if too long (only for abbreviated mode)
if (mode === "abbreviated") {
const maxLen = opts.maxLength ?? 40;
if (pwd.length > maxLen) {
pwd = `…${pwd.slice(-(maxLen - 1))}`;
}
}
}
const content = withIcon(icons.folder, pwd);
return { content: color(ctx, "path", content), visible: true };
},
};
function resolveBranchIcon(icons: IconSet, hostIcon: boolean): string {
if (!hostIcon) return icons.branch;
const host = getGitRemoteHost();
const byHost: Record<GitHost, string> = {
github: icons.github,
gitlab: icons.gitlab,
bitbucket: icons.bitbucket,
other: icons.git,
};
return host ? byHost[host] : icons.branch;
}
const gitSegment: StatusLineSegment = {
id: "git",
render(ctx) {
const icons = getIcons();
const opts = ctx.options.git ?? {};
const { branch, staged, unstaged, untracked } = ctx.git;
const gitStatus = (staged > 0 || unstaged > 0 || untracked > 0)
? { staged, unstaged, untracked }
: null;
if (!branch && !gitStatus) return { content: "", visible: false };
const isDirty = gitStatus && (gitStatus.staged > 0 || gitStatus.unstaged > 0 || gitStatus.untracked > 0);
const showBranch = opts.showBranch !== false;
const branchColor: SemanticColor = isDirty ? "gitDirty" : "gitClean";
// Build content - color branch separately from indicators
let content = "";
if (showBranch && branch) {
// Color just the branch name (icon + branch text)
const branchIcon = resolveBranchIcon(icons, opts.hostIcon === true);
content = color(ctx, branchColor, withIcon(branchIcon, branch));
}
// Add status indicators (each with their own color, not wrapped)
if (gitStatus) {
const indicators: string[] = [];
if (opts.showUnstaged !== false && gitStatus.unstaged > 0) {
indicators.push(applyColor(ctx.theme, "warning", `*${gitStatus.unstaged}`));
}
if (opts.showStaged !== false && gitStatus.staged > 0) {
indicators.push(applyColor(ctx.theme, "success", `+${gitStatus.staged}`));
}
if (opts.showUntracked !== false && gitStatus.untracked > 0) {
indicators.push(applyColor(ctx.theme, "muted", `?${gitStatus.untracked}`));
}
if (indicators.length > 0) {
const indicatorText = indicators.join(" ");
if (!content && showBranch === false) {
// No branch shown, color the git icon with branch color
content = color(ctx, branchColor, icons.git ? `${icons.git} ` : "") + indicatorText;
} else {
content += content ? ` ${indicatorText}` : indicatorText;
}
}
}
if (!content) return { content: "", visible: false };
return { content, visible: true };
},
};
const thinkingSegment: StatusLineSegment = {
id: "thinking",
render(ctx) {
const level = ctx.thinkingLevel || "off";
const levelText: Record<string, string> = {
off: "off",
minimal: "min",
low: "low",
medium: "med",
high: "high",
xhigh: "xhigh",
max: "max",
};
const label = levelText[level] || level;
const content = `think:${label}`;
if (level === "xhigh" || level === "max") {
return { content: rainbow(content), visible: true };
}
if (level === "minimal") {
return { content: color(ctx, "thinkingMinimal", content), visible: true };
}
if (level === "low") {
return { content: color(ctx, "thinkingLow", content), visible: true };
}
if (level === "medium") {
return { content: color(ctx, "thinkingMedium", content), visible: true };
}
if (level === "high") {
return { content: color(ctx, "thinkingHigh", content), visible: true };
}
return { content: color(ctx, "thinking", content), visible: true };
},
};
const subagentsSegment: StatusLineSegment = {
id: "subagents",
render() {
// Note: pi-mono doesn't have subagent tracking built-in
// This would require extension state management
// For now, return not visible
return { content: "", visible: false };
},
};
const tokenInSegment: StatusLineSegment = {
id: "token_in",
render(ctx) {
const icons = getIcons();
const { input } = ctx.usageStats;
if (!input) return { content: "", visible: false };
const content = withIcon(icons.input, formatTokens(input));
return { content: color(ctx, "tokens", content), visible: true };
},
};
const tokenOutSegment: StatusLineSegment = {
id: "token_out",
render(ctx) {
const icons = getIcons();
const { output } = ctx.usageStats;
if (!output) return { content: "", visible: false };
const content = withIcon(icons.output, formatTokens(output));
return { content: color(ctx, "tokens", content), visible: true };
},
};
const tokenTotalSegment: StatusLineSegment = {
id: "token_total",
render(ctx) {
const icons = getIcons();
const { input, output, cacheRead, cacheWrite } = ctx.usageStats;
const total = input + output + cacheRead + cacheWrite;
if (!total) return { content: "", visible: false };
const content = withIcon(icons.tokens, formatTokens(total));
return { content: color(ctx, "tokens", content), visible: true };
},
};
const costSegment: StatusLineSegment = {
id: "cost",
render(ctx) {
const { cost } = ctx.usageStats;
const usingSubscription = ctx.usingSubscription;
if (!cost && !usingSubscription) {
return { content: "", visible: false };
}
const reportedCost = cost > 0 ? `$${cost.toFixed(2)}` : null;
if (!usingSubscription) {
return reportedCost
? { content: color(ctx, "cost", reportedCost), visible: true }
: { content: "", visible: false };
}
const subscriptionSummary = ctx.subscriptionUsage ? ` ${formatSubscriptionUsageSummary(ctx.subscriptionUsage)}` : "";
const subscriptionLabel = `(sub${subscriptionSummary})`;
const subscriptionDisplay = ctx.options.cost?.subscriptionDisplay ?? "subscription";
if (subscriptionDisplay === "reported-cost" && reportedCost) {
return { content: color(ctx, "cost", reportedCost), visible: true };
}
if (subscriptionDisplay === "both" && reportedCost) {
return { content: color(ctx, "cost", `${reportedCost} ${subscriptionLabel}`), visible: true };
}
return { content: color(ctx, "cost", subscriptionLabel), visible: true };
},
};
const contextPctSegment: StatusLineSegment = {
id: "context_pct",
render(ctx) {
if (ctx.customCompactionEnabled) return { content: "", visible: false };
const icons = getIcons();
const { contextTokens, contextPercent, contextWindow } = ctx;
const autoIcon = ctx.autoCompactEnabled && icons.auto ? ` ${icons.auto}` : "";
const percentOnly = ctx.options.context?.format === "percent";
// "full" (default): tokens/window + one-decimal percentage + auto-compact icon.
// "percent": bare rounded percentage, threshold-colored, no icons.
const text = percentOnly
? `${Math.round(contextPercent)}%`
: `${formatTokens(contextTokens)}/${formatTokens(contextWindow)} (${contextPercent.toFixed(1)}%)${autoIcon}`;
// Icon outside color, text inside - use semantic colors for thresholds
let content: string;
const colored = (semantic: "context" | "contextWarn" | "contextError") =>
percentOnly ? color(ctx, semantic, text) : withIcon(icons.context, color(ctx, semantic, text));
if (contextPercent > 90) {
content = colored("contextError");
} else if (contextPercent > 70) {
content = colored("contextWarn");
} else {
content = colored("context");
}
return { content, visible: true };
},
};
const contextTotalSegment: StatusLineSegment = {
id: "context_total",
render(ctx) {
if (ctx.customCompactionEnabled) return { content: "", visible: false };
const icons = getIcons();
const window = ctx.contextWindow;
if (!window) return { content: "", visible: false };
return {
content: color(ctx, "context", withIcon(icons.context, formatTokens(window))),
visible: true,
};
},
};
const timeSpentSegment: StatusLineSegment = {
id: "time_spent",
render(ctx) {
const icons = getIcons();
const elapsed = Date.now() - ctx.sessionStartTime;
if (elapsed < 1000) return { content: "", visible: false };
return { content: withIcon(icons.time, formatDuration(elapsed)), visible: true };
},
};
const timeSegment: StatusLineSegment = {
id: "time",
render(ctx) {
const icons = getIcons();
const opts = ctx.options.time ?? {};
const now = new Date();
let hours = now.getHours();
let suffix = "";
if (opts.format === "12h") {
suffix = hours >= 12 ? "pm" : "am";
hours = hours % 12 || 12;
}
const mins = now.getMinutes().toString().padStart(2, "0");
let timeStr = `${hours}:${mins}`;
if (opts.showSeconds) {
timeStr += `:${now.getSeconds().toString().padStart(2, "0")}`;
}
timeStr += suffix;
return { content: withIcon(icons.time, timeStr), visible: true };
},
};
const sessionSegment: StatusLineSegment = {
id: "session",
render(ctx) {
const icons = getIcons();
const sessionId = ctx.sessionId;
const display = sessionId?.slice(0, 8) || "new";
return { content: withIcon(icons.session, display), visible: true };
},
};
const hostnameSegment: StatusLineSegment = {
id: "hostname",
render() {
const icons = getIcons();
const name = osHostname().split(".")[0];
return { content: withIcon(icons.host, name), visible: true };
},
};
const cacheReadSegment: StatusLineSegment = {
id: "cache_read",
render(ctx) {
const icons = getIcons();
const { cacheRead, input } = ctx.usageStats;
if (!cacheRead) return { content: "", visible: false };
let content: string;
if (ctx.options.cache_read?.format === "percent") {
// Cache hit rate: cacheRead / (input + cacheRead)
const hitRate = input + cacheRead > 0
? ((cacheRead / (input + cacheRead)) * 100).toFixed(0)
: "0";
content = [icons.cache, `${hitRate}%`].filter(Boolean).join(" ");
} else {
// "tokens" (default): raw cache-read token count
const parts = [icons.cache, icons.input, formatTokens(cacheRead)].filter(Boolean);
content = parts.join(" ");
}
return { content: color(ctx, "tokens", content), visible: true };
},
};
const cacheWriteSegment: StatusLineSegment = {
id: "cache_write",
render(ctx) {
const icons = getIcons();
const { cacheWrite } = ctx.usageStats;
if (!cacheWrite) return { content: "", visible: false };
const parts = [icons.cache, icons.output, formatTokens(cacheWrite)].filter(Boolean);
const content = parts.join(" ");
return { content: color(ctx, "tokens", content), visible: true };
},
};
const extensionStatusesSegment: StatusLineSegment = {
id: "extension_statuses",
render(ctx) {
const statuses = ctx.extensionStatuses;
if (!statuses || statuses.size === 0) return { content: "", visible: false };
// Join compact statuses with a separator
// Skip: empty strings, notification-style ("[...") shown above editor,
// and strings that are only ANSI codes with no visible text.
// Also skip statuses explicitly elevated into dedicated custom segments.
const parts: string[] = [];
for (const [statusKey, value] of statuses.entries()) {
if (ctx.hiddenExtensionStatusKeys.has(statusKey)) continue;
const normalized = value ? normalizeCompactExtensionStatus(value) : null;
if (normalized) {
parts.push(normalized);
}
}
if (parts.length === 0) return { content: "", visible: false };
// Statuses already have their own styling applied by the extensions
const content = parts.join(` ${SEP_DOT} `);
return { content, visible: true };
},
};
// ═══════════════════════════════════════════════════════════════════════════
// Segment Registry
// ═══════════════════════════════════════════════════════════════════════════
export const SEGMENTS: Record<BuiltinStatusLineSegmentId, StatusLineSegment> = {
model: modelSegment,
shell_mode: shellModeSegment,
path: pathSegment,
git: gitSegment,
thinking: thinkingSegment,
subagents: subagentsSegment,
token_in: tokenInSegment,
token_out: tokenOutSegment,
token_total: tokenTotalSegment,
cost: costSegment,
context_pct: contextPctSegment,
context_total: contextTotalSegment,
time_spent: timeSpentSegment,
time: timeSegment,
session: sessionSegment,
hostname: hostnameSegment,
cache_read: cacheReadSegment,
cache_write: cacheWriteSegment,
extension_statuses: extensionStatusesSegment,
};
function renderCustomSegment(id: `custom:${string}`, ctx: SegmentContext): RenderedSegment {
const customItemId = id.slice("custom:".length);
const custom = ctx.customItemsById.get(customItemId);
if (!custom) return { content: "", visible: false };
const rawStatus = ctx.extensionStatuses.get(custom.statusKey);
const normalizedStatus = rawStatus ? normalizeExtensionStatusValue(rawStatus) : null;
if (!normalizedStatus) {
return custom.hideWhenMissing ? { content: "", visible: false } : { content: custom.prefix ?? custom.id, visible: true };
}
let content = normalizedStatus;
if (custom.prefix) {
content = `${custom.prefix}${SEP_DOT}${content}`;
}
if (custom.color) {
content = applyColor(ctx.theme, custom.color, content);
}
return { content, visible: true };
}
export function renderSegment(id: StatusLineSegmentId, ctx: SegmentContext): RenderedSegment {
if (id.startsWith("custom:")) {
return renderCustomSegment(id, ctx);
}
const segment = SEGMENTS[id];
if (!segment) {
return { content: "", visible: false };
}
return segment.render(ctx);
}