@pi-unipi/utility 0.2.1 → 0.2.3

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/README.md CHANGED
@@ -14,6 +14,8 @@ Comprehensive utility suite for the Pi coding agent — part of the Unipi extens
14
14
  | `/unipi:cleanup` | Clean stale DBs, temp files, old sessions |
15
15
  | `/unipi:env` | Show environment info (Node, Pi, OS, paths) |
16
16
  | `/unipi:doctor` | Run diagnostics across all modules |
17
+ | `/unipi:name-badge` | Toggle name badge overlay (shows session name) |
18
+ | `/unipi:badge-gen` | Generate session name via LLM and enable badge |
17
19
 
18
20
  ### Tools
19
21
 
@@ -59,6 +61,16 @@ pi install npm:@pi-unipi/unipi
59
61
  /unipi:doctor # Run diagnostics
60
62
  ```
61
63
 
64
+ ### Name Badge
65
+
66
+ ```
67
+ /unipi:name-badge # Toggle the session name badge on/off
68
+ /unipi:badge-gen # Generate a session name via LLM
69
+ ```
70
+
71
+ The badge is a persistent HUD overlay in the top-right corner showing the current session name.
72
+ It auto-restores visibility on session restart.
73
+
62
74
  ### Batch Execution (Code)
63
75
 
64
76
  ```typescript
@@ -125,7 +137,9 @@ packages/utility/src/
125
137
  │ ├── capabilities.ts # Terminal detection
126
138
  │ └── width.ts # Width utilities
127
139
  ├── tui/
128
- └── settings-inspector.ts # Settings overlay model
140
+ ├── settings-inspector.ts # Settings overlay model
141
+ │ ├── name-badge.ts # Name badge overlay component
142
+ │ └── name-badge-state.ts # Name badge state manager
129
143
  └── tools/
130
144
  ├── batch.ts # Batch execution
131
145
  └── env.ts # Environment info
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-unipi/utility",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Utility commands and tools for Pi coding agent — lifecycle, diagnostics, cache, analytics, display, batch execution",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/commands.ts CHANGED
@@ -20,6 +20,8 @@ import {
20
20
  import { cleanupStale, formatCleanupReport } from "./lifecycle/cleanup.js";
21
21
  import { runDiagnostics, formatDiagnosticsReport } from "./diagnostics/engine.js";
22
22
  import { getEnvironmentInfo, formatEnvironmentInfo } from "./tools/env.js";
23
+ import type { NameBadgeState } from "./tui/name-badge-state.js";
24
+ import { readBadgeSettings, updateBadgeSetting, formatBadgeSettings } from "./tui/badge-settings.js";
23
25
 
24
26
  /** Send a markdown response via pi.sendMessage */
25
27
  function sendResponse(pi: ExtensionAPI, markdown: string): void {
@@ -33,6 +35,68 @@ function sendResponse(pi: ExtensionAPI, markdown: string): void {
33
35
  );
34
36
  }
35
37
 
38
+ /**
39
+ * Register name badge commands: /unipi:name-badge, /unipi:badge-gen.
40
+ */
41
+ export function registerNameBadgeCommands(
42
+ pi: ExtensionAPI,
43
+ state: NameBadgeState,
44
+ ): void {
45
+ // ─── /unipi:name-badge — toggle badge overlay ───────────────────────────
46
+ pi.registerCommand(`${UNIPI_PREFIX}${UTILITY_COMMANDS.NAME_BADGE}`, {
47
+ description: "Toggle session name badge overlay",
48
+ handler: async (_args: string, ctx: ExtensionContext) => {
49
+ if (!ctx.hasUI) {
50
+ ctx.ui.notify("Name badge requires an interactive UI.", "warning");
51
+ return;
52
+ }
53
+
54
+ const nowVisible = await state.toggle(pi, ctx);
55
+ ctx.ui.notify(
56
+ nowVisible ? "Name badge enabled" : "Name badge disabled",
57
+ "info",
58
+ );
59
+ },
60
+ });
61
+
62
+ // ─── /unipi:badge-gen — generate name via background agent ─────────────
63
+ pi.registerCommand(`${UNIPI_PREFIX}${UTILITY_COMMANDS.BADGE_GEN}`, {
64
+ description: "Generate session name via background agent and enable badge",
65
+ handler: async (_args: string, ctx: ExtensionContext) => {
66
+ if (!ctx.hasUI) {
67
+ ctx.ui.notify("Badge generation requires an interactive UI.", "warning");
68
+ return;
69
+ }
70
+
71
+ await state.generate(pi, ctx);
72
+ ctx.ui.notify("Generating session name...", "info");
73
+ },
74
+ });
75
+
76
+ // ─── /unipi:badge-toggle — configure badge settings ─────────────────────
77
+ pi.registerCommand(`${UNIPI_PREFIX}${UTILITY_COMMANDS.BADGE_TOGGLE}`, {
78
+ description: "Configure badge settings (autoGen, badgeEnabled, agentTool)",
79
+ handler: async (args: string, ctx: ExtensionContext) => {
80
+ // Parse args: /unipi:badge-settings [key] [on|off]
81
+ const parts = args.trim().split(/\s+/);
82
+ if (parts.length >= 2 && parts[0]) {
83
+ const key = parts[0] as "autoGen" | "badgeEnabled" | "agentTool";
84
+ const value = parts[1]?.toLowerCase();
85
+ if ("autoGen|badgeEnabled|agentTool".includes(key)) {
86
+ const boolValue = value === "on" || value === "true" || value === "1";
87
+ updateBadgeSetting(key, boolValue);
88
+ ctx.ui.notify(`Badge ${key} set to ${boolValue}`, "info");
89
+ return;
90
+ }
91
+ }
92
+
93
+ // Show current settings
94
+ const settings = readBadgeSettings();
95
+ sendResponse(pi, formatBadgeSettings(settings));
96
+ },
97
+ });
98
+ }
99
+
36
100
  /**
37
101
  * Register all utility commands.
38
102
  */
package/src/index.ts CHANGED
@@ -2,14 +2,14 @@
2
2
  * @pi-unipi/utility — Extension entry
3
3
  *
4
4
  * Comprehensive utilities suite for Pi coding agent:
5
- * - Commands: continue, reload, status, cleanup, env, doctor
6
- * - Tools: ctx_batch, ctx_env
5
+ * - Commands: continue, reload, status, cleanup, env, doctor, badge
6
+ * - Tools: ctx_batch, ctx_env, set_session_name
7
7
  * - Lifecycle: process management, stale cleanup
8
8
  * - Cache: TTL cache with optional persistence
9
9
  * - Analytics: lightweight event collection
10
10
  * - Diagnostics: cross-module health checks
11
11
  * - Display: terminal capabilities, width utilities
12
- * - TUI: settings inspector pattern
12
+ * - TUI: settings inspector pattern, name badge
13
13
  */
14
14
 
15
15
  import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
@@ -20,8 +20,11 @@ import {
20
20
  UTILITY_TOOLS,
21
21
  emitEvent,
22
22
  getPackageVersion,
23
+ type UnipiBadgeGenerateRequestEvent,
23
24
  } from "@pi-unipi/core";
24
- import { registerUtilityCommands } from "./commands.js";
25
+ import { registerUtilityCommands, registerNameBadgeCommands } from "./commands.js";
26
+ import { NameBadgeState } from "./tui/name-badge-state.js";
27
+ import { readBadgeSettings } from "./tui/badge-settings.js";
25
28
  import { getLifecycle } from "./lifecycle/process.js";
26
29
  import { getAnalyticsCollector } from "./analytics/collector.js";
27
30
  import { registerInfoScreen } from "./info-screen.js";
@@ -29,6 +32,9 @@ import { registerInfoScreen } from "./info-screen.js";
29
32
  /** Package version */
30
33
  const VERSION = getPackageVersion(new URL(".", import.meta.url).pathname);
31
34
 
35
+ /** Whether we've seen the first user message (for auto badge generation) */
36
+ let firstMessageSeen = false;
37
+
32
38
  /** All commands registered by this module */
33
39
  const ALL_COMMANDS = [
34
40
  UTILITY_COMMANDS.CONTINUE,
@@ -37,10 +43,13 @@ const ALL_COMMANDS = [
37
43
  UTILITY_COMMANDS.CLEANUP,
38
44
  UTILITY_COMMANDS.ENV,
39
45
  UTILITY_COMMANDS.DOCTOR,
46
+ UTILITY_COMMANDS.NAME_BADGE,
47
+ UTILITY_COMMANDS.BADGE_GEN,
48
+ UTILITY_COMMANDS.BADGE_TOGGLE,
40
49
  ].map((cmd) => `unipi:${cmd}`);
41
50
 
42
51
  /** All tools registered by this module */
43
- const ALL_TOOLS = [UTILITY_TOOLS.BATCH, UTILITY_TOOLS.ENV];
52
+ const ALL_TOOLS = [UTILITY_TOOLS.BATCH, UTILITY_TOOLS.ENV, UTILITY_TOOLS.SET_SESSION_NAME];
44
53
 
45
54
  export default function (pi: ExtensionAPI) {
46
55
  // Initialize lifecycle manager
@@ -54,17 +63,21 @@ export default function (pi: ExtensionAPI) {
54
63
  analytics.disable();
55
64
  });
56
65
 
66
+ // Initialize name badge state
67
+ const nameBadgeState = new NameBadgeState();
68
+
57
69
  // Register commands
58
70
  registerUtilityCommands(pi);
71
+ registerNameBadgeCommands(pi, nameBadgeState);
59
72
 
60
73
  // Register tools
61
- registerUtilityTools(pi);
74
+ registerUtilityTools(pi, nameBadgeState);
62
75
 
63
76
  // Register info-screen group
64
77
  registerInfoScreen(pi);
65
78
 
66
- // Session lifecycle — announce module
67
- pi.on("session_start", async () => {
79
+ // Session lifecycle — announce module + restore badge
80
+ pi.on("session_start", async (_event, ctx) => {
68
81
  emitEvent(pi, UNIPI_EVENTS.MODULE_READY, {
69
82
  name: MODULES.UTILITY,
70
83
  version: VERSION,
@@ -73,6 +86,53 @@ export default function (pi: ExtensionAPI) {
73
86
  });
74
87
 
75
88
  analytics.recordModuleLoad(MODULES.UTILITY, VERSION);
89
+
90
+ // Restore name badge if it was visible in previous session
91
+ await nameBadgeState.restore(pi, ctx);
92
+ });
93
+
94
+ // First-message hook: auto-generate session name on first user message
95
+ pi.on("input", async (_event: any, ctx: any) => {
96
+ // Only trigger on first user message
97
+ if (firstMessageSeen) return;
98
+ firstMessageSeen = true;
99
+
100
+ // Check if auto generation is enabled
101
+ const settings = readBadgeSettings();
102
+ if (!settings.autoGen) return;
103
+
104
+ // Skip if badge already has a name
105
+ const sessionName = pi.getSessionName?.();
106
+ if (sessionName) return;
107
+
108
+ // Get first message text for context
109
+ const messageText = typeof _event?.content === "string"
110
+ ? _event.content
111
+ : Array.isArray(_event?.content)
112
+ ? _event.content
113
+ .filter((c: any) => c.type === "text")
114
+ .map((c: any) => c.text)
115
+ .join(" ")
116
+ : "";
117
+
118
+ // Emit event for subagents to spawn background agent
119
+ emitEvent(pi, UNIPI_EVENTS.BADGE_GENERATE_REQUEST, {
120
+ source: "input-hook",
121
+ conversationSummary: messageText.slice(0, 500),
122
+ });
123
+
124
+ // Show badge overlay if UI available
125
+ if (ctx?.hasUI && !nameBadgeState.isVisible()) {
126
+ await nameBadgeState.show(pi, ctx);
127
+ }
128
+ });
129
+
130
+ // Listen for badge generation requests from other modules (e.g., kanboard)
131
+ pi.on(UNIPI_EVENTS.BADGE_GENERATE_REQUEST as any, async (_event: any, ctx: any) => {
132
+ // Show badge overlay if not already visible
133
+ if (!nameBadgeState.isVisible() && ctx?.hasUI) {
134
+ await nameBadgeState.show(pi, ctx);
135
+ }
76
136
  });
77
137
 
78
138
  // Track command usage
@@ -84,6 +144,8 @@ export default function (pi: ExtensionAPI) {
84
144
 
85
145
  // Session shutdown cleanup
86
146
  pi.on("session_shutdown", async () => {
147
+ nameBadgeState.hide();
148
+ firstMessageSeen = false;
87
149
  await lifecycle.shutdown("session_shutdown");
88
150
  });
89
151
  }
@@ -91,7 +153,7 @@ export default function (pi: ExtensionAPI) {
91
153
  /**
92
154
  * Register utility tools.
93
155
  */
94
- function registerUtilityTools(pi: ExtensionAPI): void {
156
+ function registerUtilityTools(pi: ExtensionAPI, nameBadgeState: NameBadgeState): void {
95
157
  // ctx_batch — atomic batch execution
96
158
  pi.registerTool({
97
159
  name: UTILITY_TOOLS.BATCH,
@@ -169,4 +231,53 @@ function registerUtilityTools(pi: ExtensionAPI): void {
169
231
  };
170
232
  },
171
233
  });
234
+
235
+ // set_session_name — set the session name for badge display
236
+ const badgeSettings = readBadgeSettings();
237
+ if (badgeSettings.agentTool) {
238
+ pi.registerTool({
239
+ name: UTILITY_TOOLS.SET_SESSION_NAME,
240
+ label: "Set Session Name",
241
+ description:
242
+ "Set the session name that appears in the badge overlay and session selector. " +
243
+ "Use this to give the current session a descriptive title. " +
244
+ "Name should be concise (max 5 words recommended).",
245
+ promptSnippet: "Set a name/title for the current session.",
246
+ parameters: {
247
+ type: "object",
248
+ properties: {
249
+ name: {
250
+ type: "string",
251
+ description: "The session name to set (max 5 words recommended).",
252
+ },
253
+ },
254
+ required: ["name"],
255
+ },
256
+ async execute(_toolCallId, params) {
257
+ const { name } = params as { name: string };
258
+ if (!name || typeof name !== "string") {
259
+ return {
260
+ content: [{ type: "text", text: "Error: name parameter is required and must be a string." }],
261
+ details: undefined,
262
+ };
263
+ }
264
+
265
+ const trimmed = name.trim();
266
+ if (trimmed.length === 0) {
267
+ return {
268
+ content: [{ type: "text", text: "Error: name cannot be empty." }],
269
+ details: undefined,
270
+ };
271
+ }
272
+
273
+ // Set the session name
274
+ nameBadgeState.setSessionName(pi, trimmed);
275
+
276
+ return {
277
+ content: [{ type: "text", text: `Session name set to: "${trimmed}"` }],
278
+ details: { name: trimmed },
279
+ };
280
+ },
281
+ });
282
+ }
172
283
  }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @pi-unipi/utility — Badge Settings Manager
3
+ *
4
+ * Manages badge configuration stored in .unipi/config/badge.json.
5
+ * Settings: autoGen, badgeEnabled, agentTool
6
+ */
7
+
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+
11
+ /** Badge settings interface */
12
+ export interface BadgeSettings {
13
+ /** Auto-generate session name on first user message */
14
+ autoGen: boolean;
15
+ /** Show the badge overlay */
16
+ badgeEnabled: boolean;
17
+ /** Enable the set_session_name tool for agents */
18
+ agentTool: boolean;
19
+ }
20
+
21
+ /** Default badge settings */
22
+ const DEFAULT_SETTINGS: BadgeSettings = {
23
+ autoGen: true,
24
+ badgeEnabled: true,
25
+ agentTool: true,
26
+ };
27
+
28
+ /** Badge settings file name */
29
+ const BADGE_CONFIG_FILE = ".unipi/config/badge.json";
30
+
31
+ /**
32
+ * Get the config file path relative to cwd.
33
+ */
34
+ function getConfigPath(): string {
35
+ return path.resolve(process.cwd(), BADGE_CONFIG_FILE);
36
+ }
37
+
38
+ /**
39
+ * Read badge settings from disk.
40
+ * Returns defaults if file doesn't exist or is malformed.
41
+ */
42
+ export function readBadgeSettings(): BadgeSettings {
43
+ try {
44
+ const configPath = getConfigPath();
45
+ if (!fs.existsSync(configPath)) return { ...DEFAULT_SETTINGS };
46
+ const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8"));
47
+ return {
48
+ autoGen: typeof parsed.autoGen === "boolean" ? parsed.autoGen : DEFAULT_SETTINGS.autoGen,
49
+ badgeEnabled: typeof parsed.badgeEnabled === "boolean" ? parsed.badgeEnabled : DEFAULT_SETTINGS.badgeEnabled,
50
+ agentTool: typeof parsed.agentTool === "boolean" ? parsed.agentTool : DEFAULT_SETTINGS.agentTool,
51
+ };
52
+ } catch {
53
+ return { ...DEFAULT_SETTINGS };
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Write badge settings to disk.
59
+ * Creates .unipi/config/ directory if needed.
60
+ */
61
+ export function writeBadgeSettings(settings: BadgeSettings): void {
62
+ try {
63
+ const configPath = getConfigPath();
64
+ const dir = path.dirname(configPath);
65
+ if (!fs.existsSync(dir)) {
66
+ fs.mkdirSync(dir, { recursive: true });
67
+ }
68
+ fs.writeFileSync(configPath, JSON.stringify(settings, null, 2) + "\n", "utf-8");
69
+ } catch {
70
+ // Best effort
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Update a single badge setting.
76
+ */
77
+ export function updateBadgeSetting<K extends keyof BadgeSettings>(
78
+ key: K,
79
+ value: BadgeSettings[K],
80
+ ): BadgeSettings {
81
+ const settings = readBadgeSettings();
82
+ settings[key] = value;
83
+ writeBadgeSettings(settings);
84
+ return settings;
85
+ }
86
+
87
+ /**
88
+ * Format badge settings for display.
89
+ */
90
+ export function formatBadgeSettings(settings: BadgeSettings): string {
91
+ const toggle = (v: boolean) => (v ? "✓ enabled" : "✗ disabled");
92
+ return [
93
+ "## Badge Settings",
94
+ "",
95
+ `| Setting | Status | Description |`,
96
+ `|---------|--------|-------------|`,
97
+ `| Auto Generate | ${toggle(settings.autoGen)} | Generate name on first message |`,
98
+ `| Badge Enabled | ${toggle(settings.badgeEnabled)} | Show badge overlay |`,
99
+ `| Agent Tool | ${toggle(settings.agentTool)} | Allow agents to call set_session_name |`,
100
+ "",
101
+ `Config: \`${BADGE_CONFIG_FILE}\``,
102
+ ].join("\n");
103
+ }
@@ -0,0 +1,299 @@
1
+ /**
2
+ * @pi-unipi/utility — Name Badge State Manager
3
+ *
4
+ * Manages the name badge overlay lifecycle:
5
+ * - Toggle visibility (persisted via pi.appendEntry)
6
+ * - Poll for session name changes every 1s
7
+ * - Restore visibility on session start
8
+ * - Generate session name via background agent event
9
+ */
10
+
11
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
12
+ import { UNIPI_EVENTS, emitEvent } from "@pi-unipi/core";
13
+ import { NameBadgeComponent } from "./name-badge.js";
14
+ import { readBadgeSettings } from "./badge-settings.js";
15
+
16
+ /** Overlay handle from ctx.ui.custom() */
17
+ interface OverlayHandle {
18
+ requestRender?: () => void;
19
+ hide?: () => void;
20
+ setHidden?: (hidden: boolean) => void;
21
+ isHidden?: () => boolean;
22
+ focus?: () => void;
23
+ unfocus?: () => void;
24
+ isFocused?: () => boolean;
25
+ }
26
+
27
+ /** Persisted badge state */
28
+ interface BadgePersistedState {
29
+ visible: boolean;
30
+ }
31
+
32
+ /** Entry type for persistence */
33
+ const BADGE_ENTRY_TYPE = "name-badge";
34
+
35
+ /** Polling interval in ms */
36
+ const POLL_INTERVAL_MS = 1000;
37
+
38
+ /** Name generation timeout in ms */
39
+ const GEN_TIMEOUT_MS = 30_000;
40
+
41
+ /**
42
+ * NameBadgeState — manages the name badge overlay.
43
+ *
44
+ * Usage:
45
+ * const state = new NameBadgeState();
46
+ * // In session_start: state.restore(pi, ctx);
47
+ * // In session_shutdown: state.hide();
48
+ * // Commands: state.toggle(pi, ctx), state.generate(pi, ctx);
49
+ */
50
+ export class NameBadgeState {
51
+ private visible = false;
52
+ private currentName: string | null = null;
53
+ private overlayHandle: OverlayHandle | null = null;
54
+ private pollTimer: ReturnType<typeof setInterval> | null = null;
55
+ private component: NameBadgeComponent | null = null;
56
+ private genTimeout: ReturnType<typeof setTimeout> | null = null;
57
+
58
+ /** Whether the badge is currently visible */
59
+ isVisible(): boolean {
60
+ return this.visible;
61
+ }
62
+
63
+ /**
64
+ * Toggle badge visibility.
65
+ * If hidden → show + start polling.
66
+ * If visible → hide + stop polling.
67
+ */
68
+ async toggle(
69
+ pi: ExtensionAPI,
70
+ ctx: { hasUI: boolean; ui: any; cwd?: string },
71
+ ): Promise<boolean> {
72
+ if (this.visible) {
73
+ this.hide();
74
+ this.persist(pi, false);
75
+ return false;
76
+ } else {
77
+ await this.show(pi, ctx);
78
+ this.persist(pi, true);
79
+ return true;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Show the badge overlay and start polling.
85
+ */
86
+ async show(
87
+ pi: ExtensionAPI,
88
+ ctx: { hasUI: boolean; ui: any; cwd?: string },
89
+ ): Promise<void> {
90
+ if (this.overlayHandle) return; // Already showing
91
+
92
+ const name = this.safeGetName(pi);
93
+ this.currentName = name;
94
+ this.visible = true;
95
+
96
+ // Store tui reference for requestRender wiring
97
+ let tuiRef: any = null;
98
+
99
+ ctx.ui.custom(
100
+ (tui: any, theme: any, _keybindings: any, _done: any) => {
101
+ tuiRef = tui;
102
+ const component = new NameBadgeComponent(name);
103
+ component.setTheme(theme);
104
+ this.component = component;
105
+
106
+ return {
107
+ render: (w: number) => component.render(w),
108
+ invalidate: () => component.invalidate(),
109
+ // No handleInput — display-only overlay
110
+ };
111
+ },
112
+ {
113
+ overlay: true,
114
+ overlayOptions: {
115
+ anchor: "top-center",
116
+ width: "100%",
117
+ nonCapturing: true,
118
+ visible: (termWidth: number) => termWidth >= 20,
119
+ },
120
+ onHandle: (handle: OverlayHandle) => {
121
+ this.overlayHandle = handle;
122
+ // Wire requestRender now that handle exists
123
+ if (tuiRef) {
124
+ (this.overlayHandle as any).requestRender = () => tuiRef.requestRender();
125
+ }
126
+ },
127
+ },
128
+ );
129
+
130
+ this.startPolling(pi);
131
+ }
132
+
133
+ /**
134
+ * Hide the badge overlay and stop polling.
135
+ */
136
+ hide(): void {
137
+ this.stopPolling();
138
+ this.clearGenTimeout();
139
+
140
+ if (this.overlayHandle) {
141
+ try {
142
+ // Use hide() to permanently remove the overlay
143
+ if (typeof this.overlayHandle.hide === "function") {
144
+ this.overlayHandle.hide();
145
+ } else if (typeof this.overlayHandle.setHidden === "function") {
146
+ this.overlayHandle.setHidden(true);
147
+ }
148
+ } catch {
149
+ // Handle may already be invalid
150
+ }
151
+ this.overlayHandle = null;
152
+ }
153
+
154
+ this.component = null;
155
+ this.visible = false;
156
+ this.currentName = null;
157
+ }
158
+
159
+ /**
160
+ * Restore badge visibility from persisted state.
161
+ * Call on session_start.
162
+ */
163
+ async restore(
164
+ pi: ExtensionAPI,
165
+ ctx: { hasUI: boolean; ui: any; cwd?: string },
166
+ ): Promise<void> {
167
+ try {
168
+ const entries = (ctx as any).sessionManager?.getEntries?.() ?? [];
169
+ const badgeEntry = entries.findLast(
170
+ (e: any) => e.type === "custom" && e.customType === BADGE_ENTRY_TYPE,
171
+ );
172
+
173
+ if (badgeEntry?.data?.visible) {
174
+ await this.show(pi, ctx);
175
+ }
176
+ } catch {
177
+ // If we can't read entries, just don't restore
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Generate a session name via background agent.
183
+ * Emits BADGE_GENERATE_REQUEST event for subagents to handle.
184
+ * Also enables the badge overlay if not visible.
185
+ */
186
+ async generate(
187
+ pi: ExtensionAPI,
188
+ ctx: { hasUI: boolean; ui: any; cwd?: string },
189
+ conversationSummary?: string,
190
+ ): Promise<void> {
191
+ // Enable badge if not visible
192
+ if (!this.visible) {
193
+ await this.show(pi, ctx);
194
+ this.persist(pi, true);
195
+ }
196
+
197
+ // Clear any previous generation timeout
198
+ this.clearGenTimeout();
199
+
200
+ // Emit event for subagents to spawn background agent
201
+ emitEvent(pi, UNIPI_EVENTS.BADGE_GENERATE_REQUEST, {
202
+ source: "command",
203
+ conversationSummary,
204
+ });
205
+
206
+ // Set timeout — if name not set within 30s, give up
207
+ this.genTimeout = setTimeout(() => {
208
+ this.genTimeout = null;
209
+ // If name is still null after timeout, the agent didn't respond
210
+ if (this.currentName === null) {
211
+ // Badge stays with placeholder — no error needed
212
+ }
213
+ }, GEN_TIMEOUT_MS);
214
+ }
215
+
216
+ /**
217
+ * Directly set the session name via pi API.
218
+ * Used by the set_session_name tool.
219
+ */
220
+ setSessionName(pi: ExtensionAPI, name: string): void {
221
+ try {
222
+ pi.setSessionName(name);
223
+ // Update component immediately (don't wait for poll)
224
+ this.currentName = name;
225
+ this.component?.setName(name);
226
+ this.overlayHandle?.requestRender?.();
227
+ // Clear generation timeout if active
228
+ this.clearGenTimeout();
229
+ } catch {
230
+ // Best effort
231
+ }
232
+ }
233
+
234
+ // ─── Private ────────────────────────────────────────────────────────
235
+
236
+ /**
237
+ * Start polling for name changes.
238
+ */
239
+ private startPolling(pi: ExtensionAPI): void {
240
+ if (this.pollTimer) return;
241
+
242
+ this.pollTimer = setInterval(() => {
243
+ const name = this.safeGetName(pi);
244
+
245
+ // Check if generation timeout should be cleared
246
+ if (name !== null && this.genTimeout) {
247
+ this.clearGenTimeout();
248
+ }
249
+
250
+ if (name !== this.currentName) {
251
+ this.currentName = name;
252
+ this.component?.setName(name);
253
+ this.overlayHandle?.requestRender?.();
254
+ }
255
+ }, POLL_INTERVAL_MS);
256
+ }
257
+
258
+ /**
259
+ * Stop polling.
260
+ */
261
+ private stopPolling(): void {
262
+ if (this.pollTimer) {
263
+ clearInterval(this.pollTimer);
264
+ this.pollTimer = null;
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Clear generation timeout.
270
+ */
271
+ private clearGenTimeout(): void {
272
+ if (this.genTimeout) {
273
+ clearTimeout(this.genTimeout);
274
+ this.genTimeout = null;
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Safely get session name, returning null on error.
280
+ */
281
+ private safeGetName(pi: ExtensionAPI): string | null {
282
+ try {
283
+ return pi.getSessionName() ?? null;
284
+ } catch {
285
+ return null;
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Persist badge visibility state.
291
+ */
292
+ private persist(pi: ExtensionAPI, visible: boolean): void {
293
+ try {
294
+ pi.appendEntry(BADGE_ENTRY_TYPE, { visible } satisfies BadgePersistedState);
295
+ } catch {
296
+ // Persistence is best-effort
297
+ }
298
+ }
299
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * @pi-unipi/utility — Name Badge Component
3
+ *
4
+ * Pure render component for the session name badge overlay.
5
+ * Displays a bordered box with opaque background and session name.
6
+ * Display-only — no input handling, no focus.
7
+ */
8
+
9
+ import type { Component } from "@mariozechner/pi-tui";
10
+ import { truncateToWidth, visibleWidth } from "@mariozechner/pi-tui";
11
+ import type { Theme } from "@mariozechner/pi-coding-agent";
12
+
13
+ /** Placeholder text when no session name is set */
14
+ const PLACEHOLDER = "Set a name";
15
+
16
+ /**
17
+ * Pad content to exact visible width.
18
+ */
19
+ function padVisible(content: string, targetWidth: number): string {
20
+ const vw = visibleWidth(content);
21
+ const pad = Math.max(0, targetWidth - vw);
22
+ return content + " ".repeat(pad);
23
+ }
24
+
25
+ /**
26
+ * NameBadgeComponent — bordered box HUD overlay showing session name.
27
+ *
28
+ * Renders a proper box with opaque background:
29
+ * ╭──────────╮
30
+ * │ Best │
31
+ * ╰──────────╯
32
+ */
33
+ export class NameBadgeComponent implements Component {
34
+ private name: string | null;
35
+ private theme: Theme | null = null;
36
+ private cachedLines: string[] | null = null;
37
+ private cachedWidth = -1;
38
+
39
+ constructor(name: string | null) {
40
+ this.name = name;
41
+ }
42
+
43
+ /** Update the displayed name */
44
+ setName(name: string | null): void {
45
+ if (name !== this.name) {
46
+ this.name = name;
47
+ this.invalidate();
48
+ }
49
+ }
50
+
51
+ /** Store theme reference for reactive color updates */
52
+ setTheme(theme: Theme): void {
53
+ this.theme = theme;
54
+ this.invalidate();
55
+ }
56
+
57
+ /** Clear cached render lines */
58
+ invalidate(): void {
59
+ this.cachedLines = null;
60
+ this.cachedWidth = -1;
61
+ }
62
+
63
+ render(width: number): string[] {
64
+ // Return cached if width unchanged
65
+ if (this.cachedLines && this.cachedWidth === width) {
66
+ return this.cachedLines;
67
+ }
68
+
69
+ const lines = this.renderBadge(width);
70
+ this.cachedLines = lines;
71
+ this.cachedWidth = width;
72
+ return this.cachedLines;
73
+ }
74
+
75
+ private renderBadge(width: number): string[] {
76
+ // Determine display text and color
77
+ let displayText: string;
78
+ let fgColor: string;
79
+ if (this.name) {
80
+ displayText = this.name;
81
+ fgColor = "accent";
82
+ } else {
83
+ displayText = PLACEHOLDER;
84
+ fgColor = "muted";
85
+ }
86
+
87
+ // Full-width box: borders take 2 cols
88
+ const innerWidth = Math.max(1, width - 2);
89
+ const maxTextWidth = Math.max(1, innerWidth - 4); // 2-cell pad each side
90
+
91
+ // Truncate name if needed
92
+ if (visibleWidth(displayText) > maxTextWidth) {
93
+ displayText = truncateToWidth(displayText, maxTextWidth - 1, "…");
94
+ }
95
+
96
+ // Center text within inner width
97
+ const textVw = visibleWidth(displayText);
98
+ const leftPad = Math.floor((innerWidth - textVw) / 2);
99
+ const rightPad = innerWidth - textVw - leftPad;
100
+
101
+ const border = (s: string) => this.theme ? this.theme.fg("accent" as any, s) : s;
102
+ const bgFn = (s: string) => this.theme ? this.theme.bg("customMessageBg" as any, s) : s;
103
+
104
+ const nameStyled = this.theme
105
+ ? this.theme.fg(fgColor as any, displayText)
106
+ : displayText;
107
+
108
+ // Build lines with opaque background spanning full width
109
+ const topLine = bgFn(border("╭" + "─".repeat(innerWidth) + "╮"));
110
+ const contentLine = bgFn(
111
+ border("│") + " ".repeat(leftPad) + nameStyled + " ".repeat(rightPad) + border("│"),
112
+ );
113
+ const bottomLine = bgFn(border("╰" + "─".repeat(innerWidth) + "╯"));
114
+
115
+ return [topLine, contentLine, bottomLine];
116
+ }
117
+ }