@mrclrchtr/supi-insights 4.7.0 → 4.9.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.
Files changed (30) hide show
  1. package/node_modules/@mrclrchtr/supi-core/README.md +29 -35
  2. package/node_modules/@mrclrchtr/supi-core/package.json +4 -7
  3. package/node_modules/@mrclrchtr/supi-core/src/api.ts +4 -6
  4. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +0 -20
  5. package/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +7 -1
  6. package/node_modules/@mrclrchtr/supi-core/src/config.ts +0 -1
  7. package/node_modules/@mrclrchtr/supi-core/src/context.ts +1 -9
  8. package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +8 -0
  9. package/node_modules/@mrclrchtr/supi-core/src/debug-timing.ts +107 -0
  10. package/node_modules/@mrclrchtr/supi-core/src/index.ts +4 -6
  11. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +54 -28
  12. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +91 -125
  13. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +10 -7
  14. package/package.json +2 -5
  15. package/src/generator.ts +44 -147
  16. package/src/html.ts +8 -55
  17. package/src/insight-schemas.ts +91 -0
  18. package/src/insights.ts +33 -32
  19. package/src/parser.ts +24 -5
  20. package/src/types.ts +4 -10
  21. package/node_modules/@mrclrchtr/supi-core/src/context/context-messages.ts +0 -119
  22. package/node_modules/@mrclrchtr/supi-core/src/progress-widget.ts +0 -189
  23. package/node_modules/@mrclrchtr/supi-core/src/settings/scoped-settings-list.ts +0 -373
  24. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-action-menu.ts +0 -102
  25. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-command.ts +0 -15
  26. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-submenus.ts +0 -141
  27. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +0 -118
  28. package/node_modules/@mrclrchtr/supi-core/src/settings-ui.ts +0 -3
  29. package/node_modules/@mrclrchtr/supi-core/src/tool-framework.ts +0 -192
  30. package/src/api.ts +0 -1
package/src/html.ts CHANGED
@@ -26,14 +26,7 @@ function generateReportJs(hourCountsJson: string): string {
26
26
  }
27
27
 
28
28
  function renderAtAGlanceHtml(insights: InsightResults): string {
29
- const atAGlance = insights.atAGlance as
30
- | {
31
- whatsWorking?: string;
32
- whatsHindering?: string;
33
- quickWins?: string;
34
- ambitiousWorkflows?: string;
35
- }
36
- | undefined;
29
+ const atAGlance = insights.atAGlance;
37
30
 
38
31
  if (!atAGlance) return "";
39
32
 
@@ -51,12 +44,7 @@ function renderAtAGlanceHtml(insights: InsightResults): string {
51
44
  }
52
45
 
53
46
  function renderProjectAreasHtml(insights: InsightResults): string {
54
- const projectAreas =
55
- (
56
- insights.projectAreas as
57
- | { areas?: Array<{ name: string; sessionCount: number; description: string }> }
58
- | undefined
59
- )?.areas ?? [];
47
+ const projectAreas = insights.projectAreas?.areas ?? [];
60
48
 
61
49
  if (projectAreas.length === 0) return "";
62
50
 
@@ -81,9 +69,7 @@ function renderProjectAreasHtml(insights: InsightResults): string {
81
69
  }
82
70
 
83
71
  function renderInteractionHtml(insights: InsightResults): string {
84
- const interactionStyle = insights.interactionStyle as
85
- | { narrative?: string; keyPattern?: string }
86
- | undefined;
72
+ const interactionStyle = insights.interactionStyle;
87
73
 
88
74
  if (!interactionStyle?.narrative) return "";
89
75
 
@@ -97,9 +83,7 @@ function renderInteractionHtml(insights: InsightResults): string {
97
83
  }
98
84
 
99
85
  function renderWhatWorksHtml(insights: InsightResults): string {
100
- const whatWorks = insights.whatWorks as
101
- | { intro?: string; impressiveWorkflows?: Array<{ title: string; description: string }> }
102
- | undefined;
86
+ const whatWorks = insights.whatWorks;
103
87
 
104
88
  if (!whatWorks?.impressiveWorkflows?.length) return "";
105
89
 
@@ -122,12 +106,7 @@ function renderWhatWorksHtml(insights: InsightResults): string {
122
106
  }
123
107
 
124
108
  function renderFrictionHtml(insights: InsightResults): string {
125
- const frictionAnalysis = insights.frictionAnalysis as
126
- | {
127
- intro?: string;
128
- categories?: Array<{ category: string; description: string; examples?: string[] }>;
129
- }
130
- | undefined;
109
+ const frictionAnalysis = insights.frictionAnalysis;
131
110
 
132
111
  if (!frictionAnalysis?.categories?.length) return "";
133
112
 
@@ -151,23 +130,7 @@ function renderFrictionHtml(insights: InsightResults): string {
151
130
  }
152
131
 
153
132
  function renderSuggestionsHtml(insights: InsightResults): string {
154
- const suggestions = insights.suggestions as
155
- | {
156
- claudeMdAdditions?: Array<{ addition: string; why: string; promptScaffold?: string }>;
157
- featuresToTry?: Array<{
158
- feature: string;
159
- oneLiner: string;
160
- whyForYou: string;
161
- exampleCode?: string;
162
- }>;
163
- usagePatterns?: Array<{
164
- title: string;
165
- suggestion: string;
166
- detail?: string;
167
- copyablePrompt?: string;
168
- }>;
169
- }
170
- | undefined;
133
+ const suggestions = insights.suggestions;
171
134
 
172
135
  if (!suggestions) return "";
173
136
 
@@ -237,17 +200,7 @@ function renderSuggestionsHtml(insights: InsightResults): string {
237
200
  }
238
201
 
239
202
  function renderHorizonHtml(insights: InsightResults): string {
240
- const horizonData = insights.onTheHorizon as
241
- | {
242
- intro?: string;
243
- opportunities?: Array<{
244
- title: string;
245
- whatsPossible: string;
246
- howToTry?: string;
247
- copyablePrompt?: string;
248
- }>;
249
- }
250
- | undefined;
203
+ const horizonData = insights.onTheHorizon;
251
204
 
252
205
  if (!horizonData?.opportunities?.length) return "";
253
206
 
@@ -272,7 +225,7 @@ function renderHorizonHtml(insights: InsightResults): string {
272
225
  }
273
226
 
274
227
  function renderFunEndingHtml(insights: InsightResults): string {
275
- const funEnding = insights.funEnding as { headline?: string; detail?: string } | undefined;
228
+ const funEnding = insights.funEnding;
276
229
 
277
230
  if (!funEnding?.headline) return "";
278
231
 
@@ -0,0 +1,91 @@
1
+ import { type Static, Type } from "typebox";
2
+
3
+ /** Validated result schemas for each generated insight section. */
4
+ export const INSIGHT_SCHEMAS = {
5
+ projectAreas: Type.Object({
6
+ areas: Type.Array(
7
+ Type.Object({
8
+ name: Type.String(),
9
+ sessionCount: Type.Number(),
10
+ description: Type.String(),
11
+ }),
12
+ ),
13
+ }),
14
+ interactionStyle: Type.Object({
15
+ narrative: Type.String(),
16
+ keyPattern: Type.String(),
17
+ }),
18
+ whatWorks: Type.Object({
19
+ intro: Type.String(),
20
+ impressiveWorkflows: Type.Array(
21
+ Type.Object({
22
+ title: Type.String(),
23
+ description: Type.String(),
24
+ }),
25
+ ),
26
+ }),
27
+ frictionAnalysis: Type.Object({
28
+ intro: Type.String(),
29
+ categories: Type.Array(
30
+ Type.Object({
31
+ category: Type.String(),
32
+ description: Type.String(),
33
+ examples: Type.Array(Type.String()),
34
+ }),
35
+ ),
36
+ }),
37
+ suggestions: Type.Object({
38
+ claudeMdAdditions: Type.Array(
39
+ Type.Object({
40
+ addition: Type.String(),
41
+ why: Type.String(),
42
+ promptScaffold: Type.String(),
43
+ }),
44
+ ),
45
+ featuresToTry: Type.Array(
46
+ Type.Object({
47
+ feature: Type.String(),
48
+ oneLiner: Type.String(),
49
+ whyForYou: Type.String(),
50
+ exampleCode: Type.String(),
51
+ }),
52
+ ),
53
+ usagePatterns: Type.Array(
54
+ Type.Object({
55
+ title: Type.String(),
56
+ suggestion: Type.String(),
57
+ detail: Type.String(),
58
+ copyablePrompt: Type.String(),
59
+ }),
60
+ ),
61
+ }),
62
+ onTheHorizon: Type.Object({
63
+ intro: Type.String(),
64
+ opportunities: Type.Array(
65
+ Type.Object({
66
+ title: Type.String(),
67
+ whatsPossible: Type.String(),
68
+ howToTry: Type.String(),
69
+ copyablePrompt: Type.String(),
70
+ }),
71
+ ),
72
+ }),
73
+ atAGlance: Type.Object({
74
+ whatsWorking: Type.String(),
75
+ whatsHindering: Type.String(),
76
+ quickWins: Type.String(),
77
+ ambitiousWorkflows: Type.String(),
78
+ }),
79
+ funEnding: Type.Object({
80
+ headline: Type.String(),
81
+ detail: Type.String(),
82
+ }),
83
+ } as const;
84
+
85
+ /** Schema type map keyed by insight section name. */
86
+ export type InsightSchemaMap = typeof INSIGHT_SCHEMAS;
87
+
88
+ /** Result types derived from the schemas used to validate model output. */
89
+ export type InsightResultMap = {
90
+ -readonly [Name in keyof InsightSchemaMap]: Static<InsightSchemaMap[Name]>;
91
+ };
package/src/insights.ts CHANGED
@@ -13,7 +13,7 @@ import type {
13
13
  } from "@earendil-works/pi-coding-agent";
14
14
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
15
15
  import { loadSupiConfig } from "@mrclrchtr/supi-core/config";
16
- import { registerDeclarativeSettings } from "@mrclrchtr/supi-core/settings";
16
+ import { defineConfigSettings, registerSettings } from "@mrclrchtr/supi-core/settings";
17
17
  import { aggregateData } from "./aggregator.ts";
18
18
  import {
19
19
  loadCachedFacets,
@@ -77,35 +77,38 @@ function getConfig(cwd: string): InsightsConfig {
77
77
 
78
78
  export default function insightsExtension(pi: ExtensionAPI) {
79
79
  // Register config-backed settings for /supi-settings
80
- registerDeclarativeSettings(pi, {
81
- id: "insights",
82
- label: "Insights",
83
- section: "insights",
84
- defaults: {
85
- enabled: true,
86
- maxSessions: MAX_SESSIONS_TO_ANALYZE,
87
- maxFacets: MAX_FACET_EXTRACTIONS,
88
- },
89
- fields: [
90
- {
91
- kind: "boolean" as const,
92
- key: "enabled",
93
- label: "Enable insights",
94
- },
95
- {
96
- kind: "number" as const,
97
- key: "maxSessions",
98
- label: "Max sessions to analyze",
99
- values: ["50", "100", "200", "500"],
100
- },
101
- {
102
- kind: "number" as const,
103
- key: "maxFacets",
104
- label: "Max facet extractions",
105
- values: ["20", "50", "100"],
80
+ registerSettings(
81
+ pi,
82
+ defineConfigSettings({
83
+ id: "insights",
84
+ label: "Insights",
85
+ section: "insights",
86
+ defaults: {
87
+ enabled: true,
88
+ maxSessions: MAX_SESSIONS_TO_ANALYZE,
89
+ maxFacets: MAX_FACET_EXTRACTIONS,
106
90
  },
107
- ],
108
- });
91
+ fields: [
92
+ {
93
+ kind: "boolean" as const,
94
+ key: "enabled",
95
+ label: "Enable insights",
96
+ },
97
+ {
98
+ kind: "number" as const,
99
+ key: "maxSessions",
100
+ label: "Max sessions to analyze",
101
+ values: ["50", "100", "200", "500"],
102
+ },
103
+ {
104
+ kind: "number" as const,
105
+ key: "maxFacets",
106
+ label: "Max facet extractions",
107
+ values: ["20", "50", "100"],
108
+ },
109
+ ],
110
+ }),
111
+ );
109
112
 
110
113
  // ── /supi-insights command ──────────────────────────────────
111
114
 
@@ -155,9 +158,7 @@ export default function insightsExtension(pi: ExtensionAPI) {
155
158
 
156
159
  const header = `# PI Insights\n\n${stats}\n${report.data.dateRange.start} to ${report.data.dateRange.end}\n`;
157
160
 
158
- const atAGlance = report.insights.atAGlance as
159
- | { whatsWorking?: string; quickWins?: string }
160
- | undefined;
161
+ const atAGlance = report.insights.atAGlance;
161
162
 
162
163
  const summaryText = atAGlance
163
164
  ? `## At a Glance\n\n${atAGlance.whatsWorking ? `**What's working:** ${atAGlance.whatsWorking}` : ""}\n\n${atAGlance.quickWins ? `**Quick wins:** ${atAGlance.quickWins}` : ""}`
package/src/parser.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // Session parser — extract metadata and transcripts from PI session entries.
2
2
 
3
3
  import { readFile } from "node:fs/promises";
4
+ import { diff } from "node:util";
4
5
  import type {
5
6
  AssistantMessage,
6
7
  Message,
@@ -10,7 +11,6 @@ import type {
10
11
  import type { FileEntry, SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
11
12
  import { migrateSessionEntries, parseSessionEntries } from "@earendil-works/pi-coding-agent";
12
13
  import { getActiveBranchEntries } from "@mrclrchtr/supi-core/session";
13
- import { diffLines } from "diff";
14
14
  import type { SessionMeta } from "./types.ts";
15
15
  import { getLanguageFromPath } from "./utils.ts";
16
16
 
@@ -41,6 +41,26 @@ const MCP_PREFIX = "mcp__";
41
41
  const WEB_SEARCH_TOOL = "web_search";
42
42
  const WEB_FETCH_TOOL = "web_fetch";
43
43
 
44
+ /** Count added and removed lines while preserving final-newline changes. */
45
+ export function countChangedLines(
46
+ oldText: string,
47
+ newText: string,
48
+ ): { added: number; removed: number } {
49
+ if (oldText === newText) return { added: 0, removed: 0 };
50
+
51
+ let added = 0;
52
+ let removed = 0;
53
+ for (const [operation] of diff(splitLines(oldText), splitLines(newText))) {
54
+ if (operation === -1) added++;
55
+ if (operation === 1) removed++;
56
+ }
57
+ return { added, removed };
58
+ }
59
+
60
+ function splitLines(text: string): string[] {
61
+ return text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
62
+ }
63
+
44
64
  export async function parseSessionFile(path: string): Promise<FileEntry[]> {
45
65
  const content = await readFile(path, { encoding: "utf-8" });
46
66
  const entries = parseSessionEntries(content);
@@ -191,10 +211,9 @@ function extractToolStats(entries: SessionEntry[]) {
191
211
  typeof input.old_string === "string" &&
192
212
  typeof input.new_string === "string"
193
213
  ) {
194
- for (const change of diffLines(input.old_string, input.new_string)) {
195
- if (change.added) linesAdded += change.count || 0;
196
- if (change.removed) linesRemoved += change.count || 0;
197
- }
214
+ const changedLines = countChangedLines(input.old_string, input.new_string);
215
+ linesAdded += changedLines.added;
216
+ linesRemoved += changedLines.removed;
198
217
  }
199
218
 
200
219
  if (toolName === "write" && typeof input.content === "string") {
package/src/types.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  // Shared types for supi-insights
2
2
 
3
+ import type { InsightResultMap } from "./insight-schemas.ts";
4
+
3
5
  export type SessionMeta = {
4
6
  sessionId: string;
5
7
  projectPath: string;
@@ -101,14 +103,6 @@ export type AggregatedData = {
101
103
  insightSectionsFailed: string[];
102
104
  };
103
105
 
104
- export type InsightSectionName =
105
- | "projectAreas"
106
- | "interactionStyle"
107
- | "whatWorks"
108
- | "frictionAnalysis"
109
- | "suggestions"
110
- | "onTheHorizon"
111
- | "atAGlance"
112
- | "funEnding";
106
+ export type InsightSectionName = keyof InsightResultMap;
113
107
 
114
- export type InsightResults = Partial<Record<InsightSectionName, unknown>>;
108
+ export type InsightResults = Partial<InsightResultMap>;
@@ -1,119 +0,0 @@
1
- // Shared context-message utilities for SuPi extensions.
2
- //
3
- // Provides a generic prune-and-reorder pattern for extensions that inject
4
- // managed context messages (via `before_agent_start` with a `customType` and
5
- // `contextToken`) and maintain them via the `context` event.
6
-
7
- /**
8
- * Minimal message shape needed for context-message operations.
9
- * Extensions cast their event.messages entries to this type.
10
- */
11
- export type ContextMessageLike = {
12
- role?: string;
13
- customType?: string;
14
- content?: unknown;
15
- details?: unknown;
16
- };
17
-
18
- /**
19
- * Extract the `contextToken` string from a message's `details` object.
20
- * Returns `null` when the token is absent or not a string.
21
- */
22
- export function getContextToken(details: unknown): string | null {
23
- if (!details || typeof details !== "object") return null;
24
- const token = (details as { contextToken?: unknown }).contextToken;
25
- return typeof token === "string" ? token : null;
26
- }
27
-
28
- /**
29
- * Find the index of the last message with `role: "user"`.
30
- * Returns `-1` when no user message exists.
31
- */
32
- export function findLastUserMessageIndex<T extends ContextMessageLike>(messages: T[]): number {
33
- for (let index = messages.length - 1; index >= 0; index--) {
34
- if (messages[index]?.role === "user") return index;
35
- }
36
- return -1;
37
- }
38
-
39
- /**
40
- * Filter stale context messages and reorder the active one before the last user message.
41
- *
42
- * - Removes all messages matching `customType` whose token differs from `activeToken`.
43
- * - When `activeToken` is `null`, removes **all** messages of that `customType`.
44
- * - If the active context message is after the last user message, moves it before.
45
- *
46
- * Returns the modified array, or the original reference when no changes were needed.
47
- */
48
- export function pruneAndReorderContextMessages<T extends ContextMessageLike>(
49
- messages: T[],
50
- customType: string,
51
- activeToken: string | null,
52
- ): T[] {
53
- // Remove stale messages of the target customType
54
- const filtered = messages.filter((message) => {
55
- if (message.customType !== customType) return true;
56
- if (!activeToken) return false;
57
- return getContextToken(message.details) === activeToken;
58
- });
59
-
60
- if (!activeToken) return filtered;
61
-
62
- // Find the active context message
63
- const contextIndex = filtered.findIndex(
64
- (message) =>
65
- message.customType === customType && getContextToken(message.details) === activeToken,
66
- );
67
- if (contextIndex === -1) return filtered;
68
-
69
- // Find the last user message
70
- const userIndex = findLastUserMessageIndex(filtered);
71
- if (userIndex === -1 || contextIndex < userIndex) return filtered;
72
-
73
- // Move context message before last user message
74
- const next = [...filtered];
75
- const [contextMessage] = next.splice(contextIndex, 1);
76
- if (!contextMessage) return filtered;
77
- next.splice(userIndex, 0, contextMessage);
78
- return next;
79
- }
80
-
81
- /**
82
- * Restore the raw prompt content on a context message that was swapped for display text.
83
- *
84
- * Extensions using `registerMessageRenderer` store their LLM-facing content in
85
- * `details.promptContent` and put a human-readable summary in `content`. This function
86
- * reverses the swap so the model sees the original prompt content.
87
- *
88
- * Returns the original array reference when no change is needed.
89
- */
90
- export function restorePromptContent<T extends ContextMessageLike>(
91
- messages: T[],
92
- customType: string,
93
- activeToken: string | null,
94
- ): T[] {
95
- if (!activeToken) return messages;
96
-
97
- const index = messages.findIndex(
98
- (message) =>
99
- message.customType === customType && getContextToken(message.details) === activeToken,
100
- );
101
- if (index === -1) return messages;
102
-
103
- const promptContent = getPromptContent(messages[index]?.details);
104
- if (!promptContent || messages[index]?.content === promptContent) return messages;
105
-
106
- const next = [...messages];
107
- next[index] = { ...next[index], content: promptContent };
108
- return next;
109
- }
110
-
111
- /**
112
- * Extract the `promptContent` string from a message's `details` object.
113
- * Returns `null` when absent or not a string.
114
- */
115
- export function getPromptContent(details: unknown): string | null {
116
- if (!details || typeof details !== "object") return null;
117
- const promptContent = (details as { promptContent?: unknown }).promptContent;
118
- return typeof promptContent === "string" ? promptContent : null;
119
- }
@@ -1,189 +0,0 @@
1
- // Generic progress widget for SuPi long-running operations.
2
- //
3
- // Provides a TUI-based progress display with animated loader, turn counts,
4
- // tool usage, and activity descriptions.
5
-
6
- import type { Theme } from "@earendil-works/pi-coding-agent";
7
- import { CancellableLoader, Container, Text } from "@earendil-works/pi-tui";
8
-
9
- // ── Types ──────────────────────────────────────────────────────────────────
10
-
11
- /** What the reviewer is currently doing and on what. */
12
- export interface CurrentFocus {
13
- /** Display label for the active tool (e.g. "Reading", "Searching", "Finding"). */
14
- label: string;
15
- /** Context detail (e.g. file path, search pattern, directory). */
16
- detail: string;
17
- }
18
-
19
- /** Progress state for widget display, compatible with child-session updates. */
20
- export interface WidgetProgress {
21
- /** Number of agent turns completed. */
22
- turns: number;
23
- /** Number of tool executions started. */
24
- toolUses: number;
25
- /** Token usage stats, if available. */
26
- tokens?: {
27
- input: number;
28
- output: number;
29
- total: number;
30
- cacheRead?: number;
31
- cacheWrite?: number;
32
- };
33
- /** Per-tool execution counts keyed by short display label (e.g. "diffs", "reads", "greps"). */
34
- toolCounts?: Record<string, number>;
35
- /** Number of distinct files inspected so far (via read_snapshot_diff / read_snapshot_file). */
36
- filesInspected?: number;
37
- /** Total files in the review snapshot. */
38
- filesTotal?: number;
39
- /** Current tool + context for the progress narrative line. */
40
- currentFocus?: CurrentFocus;
41
- /** Elapsed time in milliseconds since the operation started. */
42
- elapsedMs?: number;
43
- }
44
-
45
- // ── Widget ─────────────────────────────────────────────────────────────────
46
-
47
- /**
48
- * TUI progress widget for long-running operations.
49
- *
50
- * Two-line layout: top line shows the narrative (current focus + file progress),
51
- * bottom line shows stats (tokens, elapsed time, turns, tool counts).
52
- */
53
- export class ProgressWidget extends Container {
54
- private message: string;
55
- private progress: WidgetProgress = { turns: 0, toolUses: 0 };
56
- private loader: CancellableLoader;
57
- private tui: { requestRender(): void };
58
- private theme: Theme;
59
-
60
- constructor(tui: { requestRender(): void }, theme: Theme, message: string) {
61
- super();
62
- this.tui = tui;
63
- this.theme = theme;
64
- this.message = message;
65
- this.loader = new CancellableLoader(
66
- tui as ConstructorParameters<typeof CancellableLoader>[0],
67
- (text: string) => theme.fg("accent", text),
68
- (text: string) => theme.fg("muted", text),
69
- message,
70
- );
71
-
72
- this.renderContent();
73
- }
74
-
75
- /** AbortSignal that fires when the user presses Escape. */
76
- get signal(): AbortSignal {
77
- return this.loader.signal;
78
- }
79
-
80
- /** Callback invoked when the user presses Escape. */
81
- set onAbort(fn: (() => void) | undefined) {
82
- this.loader.onAbort = fn;
83
- }
84
-
85
- /** Delegate keyboard input to the loader. */
86
- handleInput(data: string): void {
87
- this.loader.handleInput(data);
88
- }
89
-
90
- /** Update progress state and request a re-render. */
91
- updateProgress(progress: WidgetProgress): void {
92
- this.progress = progress;
93
- this.renderContent();
94
- this.tui.requestRender();
95
- }
96
-
97
- /** Clean up the widget. */
98
- dispose(): void {
99
- this.loader.dispose();
100
- }
101
-
102
- private renderContent(): void {
103
- this.clear();
104
- this.renderTopLine();
105
- this.renderBottomLine();
106
- }
107
-
108
- private renderTopLine(): void {
109
- const topParts: string[] = [];
110
-
111
- if (this.progress.currentFocus) {
112
- const { label, detail } = this.progress.currentFocus;
113
- topParts.push(detail ? `${label}: ${detail}` : label);
114
- }
115
-
116
- if (this.progress.filesTotal && this.progress.filesTotal > 0) {
117
- const inspected = this.progress.filesInspected ?? 0;
118
- topParts.push(`${inspected}/${this.progress.filesTotal} files`);
119
- }
120
-
121
- const loaderMessage =
122
- topParts.length > 0 ? `${this.message} · ${topParts.join(" · ")}` : this.message;
123
- this.loader.setMessage(loaderMessage);
124
- this.addChild(this.loader);
125
- }
126
-
127
- private renderBottomLine(): void {
128
- const stats: string[] = [];
129
-
130
- this.appendTokenStats(stats);
131
-
132
- if (this.progress.elapsedMs !== undefined && this.progress.elapsedMs >= 1000) {
133
- stats.push(formatElapsed(this.progress.elapsedMs));
134
- }
135
-
136
- if (this.progress.turns > 0) {
137
- stats.push(`⟳ ${this.progress.turns}`);
138
- }
139
-
140
- if (this.progress.toolCounts) {
141
- const parts = Object.entries(this.progress.toolCounts)
142
- .filter(([, count]) => count > 0)
143
- .sort(([, a], [, b]) => b - a)
144
- .map(([label, count]) => `${count} ${label}`);
145
- if (parts.length > 0) stats.push(parts.join(" · "));
146
- }
147
-
148
- if (stats.length > 0) {
149
- this.addChild(new Text(this.theme.fg("dim", ` ${stats.join(" · ")}`), 1, 0));
150
- }
151
- }
152
-
153
- private appendTokenStats(stats: string[]): void {
154
- const tokens = this.progress.tokens;
155
- if (!tokens) return;
156
-
157
- stats.push(`↑ ${formatTokens(tokens.input)}`);
158
- if (tokens.cacheRead !== undefined && tokens.cacheRead > 0) {
159
- stats.push(`↲ ${formatTokens(tokens.cacheRead)}`);
160
- }
161
- if (tokens.cacheWrite !== undefined && tokens.cacheWrite > 0) {
162
- stats.push(`↱ ${formatTokens(tokens.cacheWrite)}`);
163
- }
164
- stats.push(`↓ ${formatTokens(tokens.output)}`);
165
- }
166
- }
167
-
168
- // ── Helpers ────────────────────────────────────────────────────────────────
169
-
170
- export function formatTokens(count: number): string {
171
- if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
172
- if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`;
173
- return String(count);
174
- }
175
-
176
- export function formatElapsed(ms: number): string {
177
- const totalSec = Math.floor(ms / 1000);
178
- const hours = Math.floor(totalSec / 3600);
179
- const minutes = Math.floor((totalSec % 3600) / 60);
180
- const seconds = totalSec % 60;
181
-
182
- if (hours > 0) {
183
- return `${hours}h ${minutes}m ${seconds}s`;
184
- }
185
- if (minutes > 0) {
186
- return `${minutes}m ${seconds}s`;
187
- }
188
- return `${seconds}s`;
189
- }