@lune_99/pi-dock 0.0.0-stage → 0.2.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.
@@ -0,0 +1,608 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, relative, sep } from "node:path";
3
+ import {
4
+ getAgentDir,
5
+ getLastAssistantUsage,
6
+ SettingsManager,
7
+ type ExtensionContext,
8
+ type MessageEndEvent,
9
+ type MessageStartEvent,
10
+ type MessageUpdateEvent,
11
+ type ReadonlyFooterDataProvider,
12
+ type SessionEntry,
13
+ type Theme,
14
+ } from "@earendil-works/pi-coding-agent";
15
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
16
+
17
+ /** Nerd Font glyphs, written as escapes so the source stays free of invisible private-use characters. */
18
+ const FOLDER_ICON = "";
19
+ const BRANCH_ICON = "";
20
+
21
+ export const CELL_SEPARATOR = " │ ";
22
+ const SEPARATOR_WIDTH = visibleWidth(CELL_SEPARATOR);
23
+
24
+ /**
25
+ * Every statistic owns a slot whose width is fixed up front. Values change on every turn, and a
26
+ * slot that tracked its text would shift every neighbour with it, so each value is padded to the
27
+ * widest text it can take instead.
28
+ */
29
+ const COUNT_WIDTH = 4; // "999", "9.9k", "999k", "9.9M"
30
+ const PERCENT_WIDTH = 5; // "9.9%", "99.9%", "100%"
31
+ const COST_WIDTH = 7; // "$99.999"
32
+
33
+ export interface DockUsage {
34
+ input: number;
35
+ output: number;
36
+ cacheRead: number;
37
+ cacheWrite: number;
38
+ cost: number;
39
+ /** Share of the latest prompt served from cache, in percent. */
40
+ cacheHitRate: number | undefined;
41
+ }
42
+
43
+ export interface DockTokenSpeed {
44
+ tokensPerSecond: number | undefined;
45
+ generating: boolean;
46
+ }
47
+
48
+ export type DockMessageEvent = MessageStartEvent | MessageUpdateEvent | MessageEndEvent;
49
+
50
+ /** Everything the info rows display, so rendering never touches Pi. */
51
+ export interface DockStatus {
52
+ cwd: string;
53
+ branch: string | null;
54
+ sessionName: string | undefined;
55
+ model: { provider: string; id: string; thinking: string | undefined } | undefined;
56
+ /** Pi names the provider only when more than one is available. */
57
+ showProvider: boolean;
58
+ tokenSpeed: DockTokenSpeed;
59
+ usage: DockUsage;
60
+ /** Pi reports no tokens or share until the first response after a compaction. */
61
+ context: { tokens: number | null; percent: number | null; window: number };
62
+ autoCompact: boolean;
63
+ extensionStatuses: readonly string[];
64
+ }
65
+
66
+ /**
67
+ * Pi keeps its formatter private; this matches the rounding of its own footer. The extra `G` tier
68
+ * keeps every result within four columns, which is all a counter slot reserves.
69
+ */
70
+ function formatTokens(count: number): string {
71
+ if (count < 1000) return String(count);
72
+ const units = ["k", "M", "G"];
73
+ let scaled = count / 1000;
74
+ for (let unit = 0; ; unit++) {
75
+ const text = scaled < 9.95 ? scaled.toFixed(1) : String(Math.round(scaled));
76
+ // Rounding can carry into the next unit (999.6k), which must read 1.0M, not 1000k.
77
+ if (Number(text) < 1000 || unit === units.length - 1) return text + units[unit];
78
+ scaled /= 1000;
79
+ }
80
+ }
81
+
82
+ /** Whole percent once the decimal would no longer fit, so 100% costs no extra column. */
83
+ function formatPercent(percent: number): string {
84
+ return percent >= 99.95 ? `${Math.round(percent)}%` : `${percent.toFixed(1)}%`;
85
+ }
86
+
87
+ /** Spends fewer decimals as the amount grows so the text never outgrows its slot. */
88
+ function formatCost(cost: number): string {
89
+ for (const decimals of [3, 2, 1, 0]) {
90
+ const text = `$${cost.toFixed(decimals)}`;
91
+ if (text.length <= COST_WIDTH) return text;
92
+ }
93
+ return `$${Math.round(cost)}`;
94
+ }
95
+
96
+ function abbreviateHome(cwd: string): string {
97
+ const fromHome = relative(homedir(), cwd);
98
+ if (fromHome === "") return "~";
99
+ if (fromHome === ".." || fromHome.startsWith(`..${sep}`) || isAbsolute(fromHome)) return cwd;
100
+ return `~${sep}${fromHome}`;
101
+ }
102
+
103
+ interface UsageLike {
104
+ input: number;
105
+ output: number;
106
+ cacheRead: number;
107
+ cacheWrite: number;
108
+ cost: { total: number };
109
+ }
110
+
111
+ /** Totals span every session entry, not just the current branch, as Pi's footer does. */
112
+ function summarizeUsage(entries: SessionEntry[]): DockUsage {
113
+ const usage: DockUsage = {
114
+ input: 0,
115
+ output: 0,
116
+ cacheRead: 0,
117
+ cacheWrite: 0,
118
+ cost: 0,
119
+ cacheHitRate: undefined,
120
+ };
121
+ const add = (part: UsageLike): void => {
122
+ usage.input += part.input;
123
+ usage.output += part.output;
124
+ usage.cacheRead += part.cacheRead;
125
+ usage.cacheWrite += part.cacheWrite;
126
+ usage.cost += part.cost.total;
127
+ };
128
+ for (const entry of entries) {
129
+ if (entry.type === "usage") {
130
+ add(entry.usage);
131
+ } else if (entry.type === "message") {
132
+ if (entry.message.role === "assistant") add(entry.message.usage);
133
+ else if (entry.message.role === "toolResult" && entry.message.usage) {
134
+ add(entry.message.usage);
135
+ }
136
+ } else if (
137
+ (entry.type === "branch_summary" || entry.type === "compaction") &&
138
+ entry.usage
139
+ ) {
140
+ add(entry.usage);
141
+ }
142
+ }
143
+ const latest = getLastAssistantUsage(entries);
144
+ if (latest) {
145
+ const prompt = latest.input + latest.cacheRead + latest.cacheWrite;
146
+ usage.cacheHitRate = prompt > 0 ? (latest.cacheRead / prompt) * 100 : undefined;
147
+ }
148
+ return usage;
149
+ }
150
+
151
+ function readAutoCompact(ctx: ExtensionContext): boolean {
152
+ return SettingsManager.create(ctx.cwd, getAgentDir(), {
153
+ projectTrusted: ctx.isProjectTrusted(),
154
+ }).getCompactionEnabled();
155
+ }
156
+
157
+ /** Reads the statistics Pi publishes to extensions; the dock replaces Pi's footer, so it must show them. */
158
+ export class DockStatusSource {
159
+ private usage: { key: string; value: DockUsage } | undefined;
160
+ private autoCompact: { ctx: ExtensionContext; value: boolean } | undefined;
161
+ private readonly readAutoCompact: (ctx: ExtensionContext) => boolean;
162
+ private response:
163
+ | {
164
+ ui: ExtensionContext["ui"];
165
+ sessionId: string;
166
+ requestTimestamp: number;
167
+ provider: string | undefined;
168
+ model: string | undefined;
169
+ speed: DockTokenSpeed;
170
+ }
171
+ | undefined;
172
+
173
+ observeMessage(event: DockMessageEvent, ctx: ExtensionContext): boolean {
174
+ const message = event.message;
175
+ if (message.role !== "assistant") return false;
176
+ const sessionId = ctx.sessionManager.getSessionId();
177
+ const previous = this.response;
178
+ const continuing =
179
+ event.type !== "message_start" &&
180
+ previous?.ui === ctx.ui &&
181
+ previous.sessionId === sessionId &&
182
+ previous.requestTimestamp === message.timestamp;
183
+ const generating = event.type !== "message_end";
184
+ const { output } = message.usage;
185
+ const duration = message.durationMs;
186
+ // Partial usage is not a provider-neutral live token counter; only final SDK timing is measured.
187
+ const rate =
188
+ !generating &&
189
+ Number.isFinite(output) &&
190
+ output > 0 &&
191
+ duration !== undefined &&
192
+ Number.isFinite(duration) &&
193
+ duration > 0
194
+ ? (output / duration) * 1000
195
+ : undefined;
196
+ // Virtual selections route to physical message models; keep the selection that began this response.
197
+ const provider = continuing ? previous.provider : ctx.model?.provider;
198
+ const model = continuing ? previous.model : ctx.model?.id;
199
+ const sameSelection =
200
+ previous?.ui === ctx.ui &&
201
+ previous.sessionId === sessionId &&
202
+ previous.provider === provider &&
203
+ previous.model === model;
204
+ this.response = {
205
+ ui: ctx.ui,
206
+ sessionId,
207
+ requestTimestamp: message.timestamp,
208
+ provider,
209
+ model,
210
+ speed: {
211
+ // An unfinished or cancelled response must not erase the last measured rate.
212
+ tokensPerSecond:
213
+ rate !== undefined && Number.isFinite(rate) && rate > 0
214
+ ? rate
215
+ : sameSelection
216
+ ? previous.speed.tokensPerSecond
217
+ : undefined,
218
+ generating,
219
+ },
220
+ };
221
+ return true;
222
+ }
223
+
224
+ resetTokenSpeed(): void {
225
+ this.response = undefined;
226
+ }
227
+
228
+ private collectTokenSpeed(ctx: ExtensionContext): DockTokenSpeed {
229
+ const response = this.response;
230
+ const model = ctx.model;
231
+ return model &&
232
+ response?.ui === ctx.ui &&
233
+ response.sessionId === ctx.sessionManager.getSessionId() &&
234
+ response.provider === model.provider &&
235
+ response.model === model.id
236
+ ? response.speed
237
+ : { tokensPerSecond: undefined, generating: false };
238
+ }
239
+
240
+ constructor(readCompaction: (ctx: ExtensionContext) => boolean = readAutoCompact) {
241
+ this.readAutoCompact = readCompaction;
242
+ }
243
+
244
+ collect(ctx: ExtensionContext, footerData: ReadonlyFooterDataProvider): DockStatus {
245
+ const model = ctx.model;
246
+ const level = ctx.thinkingLevel ?? "off";
247
+ const contextUsage = ctx.getContextUsage();
248
+ const statuses = [...footerData.getExtensionStatuses()]
249
+ .sort(([a], [b]) => a.localeCompare(b))
250
+ .map(([, text]) =>
251
+ text
252
+ .replace(/[\r\n\t]/g, " ")
253
+ .replace(/ +/g, " ")
254
+ .trim(),
255
+ )
256
+ .filter((text) => text.length > 0);
257
+ return {
258
+ cwd: abbreviateHome(ctx.sessionManager.getCwd()),
259
+ branch: footerData.getGitBranch(),
260
+ sessionName: ctx.sessionManager.getSessionName(),
261
+ model: model && {
262
+ provider: model.provider,
263
+ id: model.id,
264
+ thinking: model.reasoning ? (level === "off" ? "thinking off" : level) : undefined,
265
+ },
266
+ showProvider: footerData.getAvailableProviderCount() > 1,
267
+ tokenSpeed: this.collectTokenSpeed(ctx),
268
+ usage: this.collectUsage(ctx),
269
+ context: {
270
+ tokens: contextUsage?.tokens ?? null,
271
+ percent: contextUsage?.percent ?? null,
272
+ window: contextUsage?.contextWindow ?? model?.contextWindow ?? 0,
273
+ },
274
+ autoCompact: this.collectAutoCompact(ctx),
275
+ extensionStatuses: statuses,
276
+ };
277
+ }
278
+
279
+ /** The scan is linear in the session and runs every frame; entries are append-only and each append moves the leaf. */
280
+ private collectUsage(ctx: ExtensionContext): DockUsage {
281
+ const entries = ctx.sessionManager.getEntries();
282
+ const key = `${ctx.sessionManager.getSessionId()}\0${ctx.sessionManager.getLeafId()}\0${entries.length}`;
283
+ if (this.usage?.key !== key) this.usage = { key, value: summarizeUsage(entries) };
284
+ return this.usage.value;
285
+ }
286
+
287
+ /** Settings files are read once per session context, not per frame. */
288
+ private collectAutoCompact(ctx: ExtensionContext): boolean {
289
+ if (this.autoCompact?.ctx !== ctx) {
290
+ this.autoCompact = { ctx, value: this.readAutoCompact(ctx) };
291
+ }
292
+ return this.autoCompact.value;
293
+ }
294
+ }
295
+
296
+ const MAX_SPEED_VALUE_WIDTH = 6;
297
+
298
+ function formatTokenSpeed(rate: number | undefined): string | undefined {
299
+ if (rate === undefined || !Number.isFinite(rate) || rate <= 0) return undefined;
300
+ if (rate < 0.1) return "<0.1";
301
+ for (const decimals of [1, 0]) {
302
+ const text = rate.toFixed(decimals);
303
+ if (text.length <= MAX_SPEED_VALUE_WIDTH) return text;
304
+ }
305
+ return rate.toExponential(0);
306
+ }
307
+
308
+ /** Drop optional segments whole before spending any of the model's own columns. */
309
+ export function modelSegmentVariants(status: DockStatus, theme: Theme): string[] {
310
+ const model = status.model;
311
+ const name = model?.id ?? "no-model";
312
+ const thinking = model?.thinking ? theme.fg("dim", ` • ${model.thinking}`) : "";
313
+ const bare = name + thinking;
314
+ const withProvider =
315
+ status.showProvider && model ? theme.fg("accent", `(${model.provider}) `) + bare : bare;
316
+ if (!model) return [bare];
317
+ const value = formatTokenSpeed(status.tokenSpeed.tokensPerSecond);
318
+ if (value === undefined) return [...new Set([withProvider, bare])];
319
+ const speed = theme.fg(status.tokenSpeed.generating ? "accent" : "dim", ` • ${value} tok/s`);
320
+ return [...new Set([withProvider + speed, bare + speed, withProvider, bare])];
321
+ }
322
+
323
+ export function renderModelSegment(status: DockStatus, theme: Theme, width: number): string {
324
+ const variants = modelSegmentVariants(status, theme);
325
+ return (
326
+ variants.find((text) => visibleWidth(text) <= width) ??
327
+ truncateToWidth(variants.at(-1)!, width)
328
+ );
329
+ }
330
+
331
+ /**
332
+ * Left-aligned, so a label stays one column after its bar and a growing number spends only the
333
+ * padding behind it.
334
+ */
335
+ function padEnd(text: string, width: number): string {
336
+ const gap = width - visibleWidth(text);
337
+ return gap >= 0 ? text + " ".repeat(gap) : truncateToWidth(text, width);
338
+ }
339
+
340
+ /** Right-aligned, for the numerator of a fraction, so its slash never moves. */
341
+ function padStart(text: string, width: number): string {
342
+ const gap = width - visibleWidth(text);
343
+ return gap >= 0 ? " ".repeat(gap) + text : truncateToWidth(text, width);
344
+ }
345
+
346
+ const CONTEXT_JOINER = " · ";
347
+ const CONTEXT_WIDTH = COUNT_WIDTH + 1 + COUNT_WIDTH + visibleWidth(CONTEXT_JOINER) + PERCENT_WIDTH;
348
+
349
+ /**
350
+ * Tokens in use over the window, then the share. Turns warning/error at the same thresholds as Pi's
351
+ * own footer. The window is constant for a model, so only the used count and share need room to grow.
352
+ */
353
+ export function renderContextCell(status: DockStatus, theme: Theme): string {
354
+ const { tokens, percent, window } = status.context;
355
+ const used = padStart(tokens === null ? "?" : formatTokens(tokens), COUNT_WIDTH);
356
+ const share = percent === null ? "?" : formatPercent(percent);
357
+ return theme.fg(
358
+ (percent ?? 0) > 90 ? "error" : (percent ?? 0) > 70 ? "warning" : "muted",
359
+ padEnd(`${used}/${formatTokens(window)}${CONTEXT_JOINER}${share}`, CONTEXT_WIDTH),
360
+ );
361
+ }
362
+
363
+ interface StatSlot {
364
+ /** Higher survives longer when the row is too narrow. */
365
+ keep: number;
366
+ /** Columns reserved for the slot with every part present, whatever the values are. */
367
+ width: number;
368
+ /** A slot without data keeps its columns but draws neither its bar nor any text. */
369
+ hasData(status: DockStatus): boolean;
370
+ render(status: DockStatus, theme: Theme): string;
371
+ }
372
+
373
+ /**
374
+ * Each counter keeps its own columns, so one that is still zero is blank rather than absent and the
375
+ * counter after it never moves.
376
+ */
377
+ function counters(theme: Theme, ...parts: [label: string, count: number][]): string {
378
+ return parts
379
+ .map(([label, count]) =>
380
+ padEnd(
381
+ count > 0 ? theme.fg("muted", label + formatTokens(count)) : "",
382
+ 1 + COUNT_WIDTH,
383
+ ),
384
+ )
385
+ .join(" ");
386
+ }
387
+
388
+ /** A single counter with a slot to itself, drawn only once it is above zero. */
389
+ function counterSlot(keep: number, label: string, count: (usage: DockUsage) => number): StatSlot {
390
+ return {
391
+ keep,
392
+ width: 1 + COUNT_WIDTH,
393
+ hasData: ({ usage }) => count(usage) > 0,
394
+ render: ({ usage }, theme) => theme.fg("muted", label + formatTokens(count(usage))),
395
+ };
396
+ }
397
+
398
+ /**
399
+ * Which slots exist depends on the session, never on the numbers: auto-compaction is a setting
400
+ * read once per session, so (auto) only claims its columns when it will be shown. Whether a slot
401
+ * is drawn is a separate question, answered by `hasData`.
402
+ *
403
+ * Slots run from the one most likely to stay empty to the ones always drawn, so blank slots gather
404
+ * on the left, where they read as part of the gap after the directory, not as a hole between numbers.
405
+ * `keep` orders the drop independently: the counters and cost give way first, while the hit rate
406
+ * stays until only context and (auto) share the row.
407
+ */
408
+ function statSlots(status: DockStatus): StatSlot[] {
409
+ const slots: StatSlot[] = [
410
+ // Cache writes come first: many providers never report them, and their slot then stays blank.
411
+ counterSlot(1, "W", (usage) => usage.cacheWrite),
412
+ counterSlot(2, "R", (usage) => usage.cacheRead),
413
+ {
414
+ keep: 5,
415
+ width: 3 + PERCENT_WIDTH,
416
+ // A provider that reports no cache traffic has no hit rate worth quoting.
417
+ hasData: ({ usage }) =>
418
+ (usage.cacheRead > 0 || usage.cacheWrite > 0) && usage.cacheHitRate !== undefined,
419
+ render: ({ usage }, theme) =>
420
+ theme.fg("muted", `CH ${formatPercent(usage.cacheHitRate ?? 0)}`),
421
+ },
422
+ {
423
+ keep: 3,
424
+ width: 2 * (1 + COUNT_WIDTH) + 1,
425
+ hasData: ({ usage }) => usage.input > 0 || usage.output > 0,
426
+ render: ({ usage }, theme) => counters(theme, ["↑", usage.input], ["↓", usage.output]),
427
+ },
428
+ {
429
+ keep: 4,
430
+ width: COST_WIDTH,
431
+ hasData: ({ usage }) => usage.cost > 0,
432
+ render: ({ usage }, theme) => theme.fg("muted", formatCost(usage.cost)),
433
+ },
434
+ {
435
+ keep: 7,
436
+ width: CONTEXT_WIDTH,
437
+ hasData: () => true,
438
+ render: (current, theme) => renderContextCell(current, theme),
439
+ },
440
+ ];
441
+ if (status.autoCompact) {
442
+ slots.push({
443
+ keep: 6,
444
+ width: 6,
445
+ hasData: () => true,
446
+ render: (_current, theme) => theme.fg("accent", "(auto)"),
447
+ });
448
+ }
449
+ return slots;
450
+ }
451
+
452
+ /** Every slot spends one separator, before it: the first one divides the statistics from the directory. */
453
+ function slotsWidth(slots: readonly StatSlot[]): number {
454
+ return slots.reduce((sum, slot) => sum + SEPARATOR_WIDTH + slot.width, 0);
455
+ }
456
+
457
+ /**
458
+ * Drops the least important slots until the rest fit. Only the reserved widths are compared, so
459
+ * the same terminal width always yields the same slots, whatever the numbers currently say.
460
+ */
461
+ function fitSlots(slots: StatSlot[], budget: number): StatSlot[] {
462
+ const kept = [...slots];
463
+ while (kept.length > 1 && slotsWidth(kept) > budget) {
464
+ const weakest = kept.reduce((low, slot) => (slot.keep < low.keep ? slot : low));
465
+ kept.splice(kept.indexOf(weakest), 1);
466
+ }
467
+ return kept;
468
+ }
469
+
470
+ /** The full path first, then fewer leading segments, down to the folder that names the project. */
471
+ function pathVariants(path: string): string[] {
472
+ const segments = path.split(sep);
473
+ const variants = [path];
474
+ for (let count = segments.length - 1; count >= 1; count--) {
475
+ const candidate = `…${sep}${segments.slice(-count).join(sep)}`;
476
+ if (visibleWidth(candidate) < visibleWidth(variants.at(-1)!)) variants.push(candidate);
477
+ }
478
+ return variants;
479
+ }
480
+
481
+ interface WorkspaceText {
482
+ folder: string;
483
+ branch: string;
484
+ session: string;
485
+ }
486
+
487
+ function branchOnly(status: DockStatus): WorkspaceText | undefined {
488
+ return status.branch
489
+ ? { folder: "", branch: ` ${BRANCH_ICON} (${status.branch})`, session: "" }
490
+ : undefined;
491
+ }
492
+
493
+ /**
494
+ * The directory side of the info row, richest first. Leading path segments go first, then the
495
+ * session name, then the project folder; the branch stays as long as anything is drawn.
496
+ */
497
+ function workspaceVariants(status: DockStatus): WorkspaceText[] {
498
+ const branch = status.branch ? ` ${BRANCH_ICON} (${status.branch})` : "";
499
+ const session = status.sessionName ? ` • ${status.sessionName}` : "";
500
+ const folders = pathVariants(status.cwd).map((path) => ` ${FOLDER_ICON} ${path}`);
501
+ const variants = folders.map((folder) => ({ folder, branch, session: "" }));
502
+ if (session) variants.unshift(...folders.map((folder) => ({ folder, branch, session })));
503
+ const bare = branchOnly(status);
504
+ if (bare) variants.push(bare);
505
+ return variants;
506
+ }
507
+
508
+ function workspaceWidth(text: WorkspaceText): number {
509
+ return visibleWidth(text.folder + text.branch + text.session);
510
+ }
511
+
512
+ export interface InfoRowParts {
513
+ workspace: boolean;
514
+ usage: boolean;
515
+ }
516
+
517
+ /**
518
+ * The most the project folder and branch claim before any statistic is placed. Past it only the
519
+ * branch is reserved, so a long branch name costs the folder, not a statistic.
520
+ */
521
+ const MAX_WORKSPACE_RESERVE = 40;
522
+
523
+ /**
524
+ * Room kept for the project folder and branch; the leading path segments and the session name
525
+ * only use what the statistics leave. Neither the folder nor the branch changes with the numbers,
526
+ * so a counter appears or vanishes only when the terminal width or the branch changes.
527
+ */
528
+ function workspaceReserve(status: DockStatus): number {
529
+ const variants = workspaceVariants(status);
530
+ const project = variants.findLast((text) => text.folder !== "")!;
531
+ const bare = branchOnly(status);
532
+ return Math.min(
533
+ workspaceWidth(project),
534
+ Math.max(MAX_WORKSPACE_RESERVE, bare ? workspaceWidth(bare) : 0),
535
+ );
536
+ }
537
+
538
+ function reserveSlots(status: DockStatus, width: number, workspace: boolean): StatSlot[] {
539
+ return fitSlots(statSlots(status), width - (workspace ? workspaceReserve(status) : 0));
540
+ }
541
+
542
+ /**
543
+ * Where the info row draws the bar before each reserved slot, counted in columns from the right
544
+ * edge, leftmost first. The dock row reuses one for its model divider so both rows share a bar.
545
+ */
546
+ export function statColumns(status: DockStatus, width: number, workspace: boolean): number[] {
547
+ const slots = reserveSlots(status, width, workspace);
548
+ return slots.map((_slot, index) => slotsWidth(slots.slice(index)));
549
+ }
550
+
551
+ /**
552
+ * Working directory and branch on the left, usage statistics on a grid of reserved slots against
553
+ * the right edge. The grid follows from the terminal width, project folder and branch, and every
554
+ * slot keeps its columns whether or not it has data, so arriving or changing numbers never move a
555
+ * bar or a label.
556
+ */
557
+ export function renderInfoRow(
558
+ status: DockStatus,
559
+ width: number,
560
+ theme: Theme,
561
+ parts: InfoRowParts = { workspace: true, usage: true },
562
+ ): string {
563
+ const reserved = parts.usage ? reserveSlots(status, width, parts.workspace) : [];
564
+ const reservedWidth = slotsWidth(reserved);
565
+ const firstDrawn = reserved.findIndex((slot) => slot.hasData(status));
566
+ const grid = reserved
567
+ .map((slot, index) => {
568
+ if (!slot.hasData(status)) return " ".repeat(SEPARATOR_WIDTH + slot.width);
569
+ // With no directory beside it, the leftmost bar would divide the statistics from nothing.
570
+ const bar =
571
+ index === firstDrawn && !parts.workspace
572
+ ? " ".repeat(SEPARATOR_WIDTH)
573
+ : theme.fg("dim", CELL_SEPARATOR);
574
+ return bar + padEnd(slot.render(status, theme), slot.width);
575
+ })
576
+ .join("");
577
+ // Only the context slot is left once even it overflows; its blank leading columns give way first.
578
+ const right =
579
+ firstDrawn < 0
580
+ ? ""
581
+ : visibleWidth(grid) > width
582
+ ? truncateToWidth(grid.trimStart(), width)
583
+ : grid;
584
+
585
+ let left = "";
586
+ if (parts.workspace) {
587
+ // Fitted against the whole grid, not the drawn slots, so the directory does not move either.
588
+ const room = width - reservedWidth;
589
+ const text = workspaceVariants(status).find((variant) => workspaceWidth(variant) <= room);
590
+ if (text) {
591
+ left =
592
+ (text.folder && theme.fg("muted", text.folder)) +
593
+ (text.branch && theme.fg("accent", text.branch)) +
594
+ (text.session && theme.fg("dim", text.session));
595
+ }
596
+ }
597
+ return left + " ".repeat(Math.max(0, width - visibleWidth(left) - visibleWidth(right))) + right;
598
+ }
599
+
600
+ /** Statuses set through `ctx.ui.setStatus()` lived in Pi's footer, so the dock keeps showing them. */
601
+ export function renderStatusRow(
602
+ statuses: readonly string[],
603
+ width: number,
604
+ theme: Theme,
605
+ ): string | undefined {
606
+ if (statuses.length === 0) return undefined;
607
+ return truncateToWidth(` ${statuses.join(" ")}`, width, theme.fg("dim", "…"));
608
+ }
package/src/index.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ bindSettings,
4
+ registerSettingsPanel,
5
+ scopedExtension,
6
+ } from "@lune_99/pi-lune-extensions-core";
7
+ import { openSettingsPanel } from "@lune_99/pi-lune-extensions-core/panel/tui";
8
+ import { DockController } from "./dock-controller.ts";
9
+ import { dockPanel } from "./dock-panel.ts";
10
+ import { dockSettings } from "./dock-settings.ts";
11
+
12
+ export default scopedExtension((pi, resources) => {
13
+ const dock = new DockController();
14
+ const settings = resources.use(bindSettings(pi, dockSettings));
15
+ resources.use(registerSettingsPanel(dockPanel, settings));
16
+ // Dock teardown runs before the borrowed settings' own shutdown.
17
+ resources.defer(() => dock.detach());
18
+
19
+ resources.defer(
20
+ pi.on("session_start", async (_event, ctx: ExtensionContext) => {
21
+ dock.detach();
22
+ let attached = false;
23
+ const view = await settings.view(ctx);
24
+ const apply = () => {
25
+ const { enabled, ...appearance } = view.snapshot();
26
+ dock.configure(appearance);
27
+ // Re-attaching would drop focus and the cell window, so only enabling or disabling does it.
28
+ if (enabled && !attached) dock.attach(ctx);
29
+ else if (!enabled && attached) dock.detach();
30
+ attached = enabled;
31
+ };
32
+ apply();
33
+ // Style, visibility and enabling take effect without a restart; the view retires the subscription.
34
+ view.subscribe(apply);
35
+ }),
36
+ );
37
+ resources.defer(pi.on("session_before_tree", () => dock.resetInteraction()));
38
+ resources.defer(pi.on("session_tree", () => dock.resetTokenSpeed()));
39
+ resources.defer(pi.on("message_start", (event, ctx) => dock.observeMessage(event, ctx)));
40
+ resources.defer(pi.on("message_update", (event, ctx) => dock.observeMessage(event, ctx)));
41
+ resources.defer(pi.on("message_end", (event, ctx) => dock.observeMessage(event, ctx)));
42
+
43
+ pi.registerCommand("dock", {
44
+ description: "Open Lune Dock settings",
45
+ handler: async (_args, ctx) => {
46
+ if (ctx.mode !== "tui") {
47
+ ctx.ui.notify("Dock settings require interactive TUI mode", "warning");
48
+ return;
49
+ }
50
+ await openSettingsPanel(ctx, { section: dockPanel.id });
51
+ },
52
+ });
53
+ });