@blackbelt-technology/pi-dashboard-extension 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.pi/skills/pi-dashboard/SKILL.md +134 -0
  2. package/.pi/skills/pi-dashboard/references/api-reference.md +470 -0
  3. package/.pi/skills/pi-dashboard/references/recipes.md +252 -0
  4. package/.pi/skills/pi-dashboard/scripts/dashboard-api.sh +75 -0
  5. package/package.json +38 -0
  6. package/src/__tests__/ask-user-tool.test.ts +432 -0
  7. package/src/__tests__/command-handler.test.ts +712 -0
  8. package/src/__tests__/connection.test.ts +344 -0
  9. package/src/__tests__/credentials-updated.test.ts +26 -0
  10. package/src/__tests__/dashboard-default-adapter.test.ts +77 -0
  11. package/src/__tests__/dev-build.test.ts +79 -0
  12. package/src/__tests__/enrich-model-metadata.test.ts +201 -0
  13. package/src/__tests__/event-forwarder.test.ts +89 -0
  14. package/src/__tests__/fork-entryid-timing.test.ts +100 -0
  15. package/src/__tests__/git-info.test.ts +124 -0
  16. package/src/__tests__/git-link-builder.test.ts +102 -0
  17. package/src/__tests__/openspec-activity-detector.test.ts +232 -0
  18. package/src/__tests__/openspec-poller.test.ts +124 -0
  19. package/src/__tests__/process-metrics.test.ts +47 -0
  20. package/src/__tests__/process-scanner-kill.test.ts +61 -0
  21. package/src/__tests__/process-scanner.test.ts +202 -0
  22. package/src/__tests__/prompt-bus-wiring.test.ts +791 -0
  23. package/src/__tests__/prompt-bus.test.ts +469 -0
  24. package/src/__tests__/prompt-expander.test.ts +54 -0
  25. package/src/__tests__/provider-register-reload.test.ts +394 -0
  26. package/src/__tests__/server-auto-start.test.ts +258 -0
  27. package/src/__tests__/server-launcher.test.ts +61 -0
  28. package/src/__tests__/server-probe.test.ts +25 -0
  29. package/src/__tests__/session-switch.test.ts +139 -0
  30. package/src/__tests__/session-sync.test.ts +55 -0
  31. package/src/__tests__/source-detector.test.ts +73 -0
  32. package/src/__tests__/stats-extractor.test.ts +92 -0
  33. package/src/__tests__/tui-prompt-adapter.test.ts +207 -0
  34. package/src/__tests__/watchdog.test.ts +161 -0
  35. package/src/ask-user-tool.ts +352 -0
  36. package/src/bridge-context.ts +64 -0
  37. package/src/bridge.ts +1182 -0
  38. package/src/command-handler.ts +533 -0
  39. package/src/connection.ts +204 -0
  40. package/src/dashboard-default-adapter.ts +37 -0
  41. package/src/dev-build.ts +39 -0
  42. package/src/event-forwarder.ts +40 -0
  43. package/src/flow-event-wiring.ts +85 -0
  44. package/src/git-info.ts +55 -0
  45. package/src/git-link-builder.ts +112 -0
  46. package/src/model-tracker.ts +56 -0
  47. package/src/pi-env.d.ts +37 -0
  48. package/src/process-metrics.ts +70 -0
  49. package/src/process-scanner.ts +430 -0
  50. package/src/prompt-bus.ts +240 -0
  51. package/src/prompt-expander.ts +108 -0
  52. package/src/provider-register.ts +564 -0
  53. package/src/server-auto-start.ts +113 -0
  54. package/src/server-launcher.ts +126 -0
  55. package/src/server-probe.ts +33 -0
  56. package/src/session-sync.ts +155 -0
  57. package/src/source-detector.ts +26 -0
package/src/bridge.ts ADDED
@@ -0,0 +1,1182 @@
1
+ /**
2
+ * PI Dashboard Bridge Extension
3
+ *
4
+ * Global extension that connects to the dashboard server,
5
+ * forwards all pi events, and relays commands back.
6
+ */
7
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
8
+ import { Loader } from "@mariozechner/pi-tui";
9
+ import { ConnectionManager } from "./connection.js";
10
+ import { detectSessionSource } from "./source-detector.js";
11
+ import { mapEventToProtocol } from "./event-forwarder.js";
12
+ import { createCommandHandler } from "./command-handler.js";
13
+ import fs from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { loadConfig, ensureConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
18
+ import { runDevBuild } from "./dev-build.js";
19
+ import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
20
+ import { discoverDashboard } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
21
+ import { launchServer } from "./server-launcher.js";
22
+ import { autoStartServer } from "./server-auto-start.js";
23
+ import type { ServerToExtensionMessage } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
24
+ import { expandPromptTemplateFromDisk } from "./prompt-expander.js";
25
+
26
+ import { PromptBus } from "./prompt-bus.js";
27
+ import { DashboardDefaultAdapter } from "./dashboard-default-adapter.js";
28
+ import { registerAskUserTool } from "./ask-user-tool.js";
29
+ import { activate as activateProviderRegister, onProviderChanged, reloadProviders } from "./provider-register.js";
30
+ import type { FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
31
+ import { startMetricsMonitor, stopMetricsMonitor, collectMetrics } from "./process-metrics.js";
32
+ import { scanChildProcesses } from "./process-scanner.js";
33
+ import type { BridgeContext } from "./bridge-context.js";
34
+ import { filterHiddenCommands, extractFirstMessage, getCurrentModelString } from "./bridge-context.js";
35
+ import { sendStateSync as _sendStateSync, replaySessionEntries as _replaySessionEntries, handleSessionChange as _handleSessionChange } from "./session-sync.js";
36
+ import { sendModelUpdateIfChanged as _sendModelUpdateIfChanged, sendSessionNameIfChanged as _sendSessionNameIfChanged, sendGitInfoIfChanged as _sendGitInfoIfChanged } from "./model-tracker.js";
37
+ import { registerFlowEventListeners, FLOW_EVENT_MAP, SUBAGENT_EVENT_MAP } from "./flow-event-wiring.js";
38
+
39
+ const HEARTBEAT_INTERVAL = 15_000;
40
+ const GIT_POLL_INTERVAL = 30_000;
41
+ const PROCESS_SCAN_INTERVAL = 10_000;
42
+
43
+
44
+
45
+ // Use `process` (not `globalThis`) to survive jiti module cache invalidation
46
+ // AND to share state across isolated extension contexts (vm sandboxes).
47
+ const BRIDGE_KEY = "__pi_dashboard_bridge__";
48
+ interface BridgeState {
49
+ cleanup?: () => void;
50
+ sessionId?: string;
51
+ ctx?: any;
52
+ modelRegistry?: any;
53
+ hasUI?: boolean;
54
+ /** Monotonic generation counter — stale listeners bail out when mismatched */
55
+ generation?: number;
56
+ /** The pi instance that owns the bridge (used to detect subagent re-entry) */
57
+ pi?: ExtensionAPI;
58
+ /** All connection instances from any bridge incarnation (for cleanup) */
59
+ connections?: ConnectionManager[];
60
+ /** All interval timers from any bridge incarnation (for cleanup) */
61
+ timers?: ReturnType<typeof setInterval>[];
62
+ /** True when the agent is currently in a turn (between agent_start and agent_end) */
63
+ isAgentStreaming?: boolean;
64
+ }
65
+ function getBridgeState(): BridgeState {
66
+ if (!(process as any)[BRIDGE_KEY]) {
67
+ (process as any)[BRIDGE_KEY] = {};
68
+ }
69
+ return (process as any)[BRIDGE_KEY];
70
+ }
71
+
72
+ export default function (pi: ExtensionAPI) {
73
+ try {
74
+ // Activate provider management before bridge init so providers are
75
+ // registered before session_start fires and models_list is sent.
76
+ activateProviderRegister(pi);
77
+
78
+ // Anthropic-messages payload transforms (system prompt rewrite + tool
79
+ // filter/remap) are handled by the installed @benvargas/pi-claude-code-use
80
+ // package when present. No local duplication here.
81
+
82
+ initBridge(pi);
83
+ } catch (err) {
84
+ // Never crash the host pi agent — dashboard is non-essential
85
+ console.error("[dashboard] Bridge init failed:", err);
86
+ }
87
+ }
88
+
89
+
90
+
91
+
92
+
93
+ function initBridge(pi: ExtensionAPI) {
94
+ const prev = getBridgeState();
95
+
96
+ // If bridge is already active for a different pi instance (e.g. a subagent
97
+ // loading extensions in the same process), skip initialization to avoid
98
+ // invalidating the parent session's bridge connection and event forwarding.
99
+ if (prev.generation && prev.generation > 0 && prev.pi && prev.pi !== pi) {
100
+ return;
101
+ }
102
+
103
+ prev.cleanup?.();
104
+ prev.cleanup = undefined;
105
+
106
+ // Disconnect ALL orphaned connections from previous bridge incarnations
107
+ if (prev.connections) {
108
+ for (const conn of prev.connections) {
109
+ conn.disconnect();
110
+ }
111
+ }
112
+ prev.connections = [];
113
+ // Clear ALL orphaned timers
114
+ if (prev.timers) {
115
+ for (const t of prev.timers) {
116
+ clearInterval(t);
117
+ }
118
+ }
119
+ prev.timers = [];
120
+
121
+ // Bump generation so stale listeners from previous initBridge calls bail out
122
+ const generation = (prev.generation ?? 0) + 1;
123
+ prev.generation = generation;
124
+ prev.pi = pi;
125
+ /** Return true if this bridge instance is still the active one */
126
+ function isActive(): boolean {
127
+ return getBridgeState().generation === generation;
128
+ }
129
+
130
+ let sessionId: string = prev.sessionId ?? crypto.randomUUID();
131
+ let sessionReady = false; // true after session_start has run
132
+ let lastSessionFile: string | undefined;
133
+ let lastSessionDir: string | undefined;
134
+ let lastFirstMessage: string | undefined;
135
+ let pendingDefaultModel: string | null = null; // non-null if default model not yet applied (custom provider not ready)
136
+
137
+ /** Try to apply the default model from config. Returns the model string if not found (pending), null if applied or no default. */
138
+ function applyDefaultModel(): string | null {
139
+ const freshConfig = loadConfig();
140
+ if (!freshConfig.defaultModel || !cachedModelRegistry) return null;
141
+ const slashIdx = freshConfig.defaultModel.indexOf("/");
142
+ if (slashIdx <= 0) return null;
143
+ const provider = freshConfig.defaultModel.slice(0, slashIdx);
144
+ const modelId = freshConfig.defaultModel.slice(slashIdx + 1);
145
+ try {
146
+ const found = cachedModelRegistry.find(provider, modelId);
147
+ if (found) {
148
+ (pi as any).setModel(found).then(() => {
149
+ setTimeout(() => sendModelUpdateIfChanged(), 50);
150
+ }).catch(() => {});
151
+ return null; // applied
152
+ }
153
+ } catch { /* ignore */ }
154
+ return freshConfig.defaultModel; // not found yet — pending
155
+ }
156
+
157
+ /** Query pi-flows for available flows via synchronous event RPC */
158
+ function getFlowsList(): FlowInfo[] {
159
+ const probe: any = {};
160
+ try {
161
+ pi.events?.emit("flow:list-flows", probe);
162
+ } catch { /* ignore */ }
163
+ return (probe.flows as FlowInfo[] | undefined) ?? [];
164
+ }
165
+
166
+ /** Send flows_list message to the dashboard server */
167
+ function sendFlowsList() {
168
+ const flows = getFlowsList();
169
+ console.error(`[dashboard] sendFlowsList: ${flows.length} flows, sessionId=${sessionId.slice(0,8)}`);
170
+ connection.send({ type: "flows_list", sessionId, flows });
171
+ }
172
+
173
+
174
+ let heartbeatTimer: ReturnType<typeof setInterval> | null = null;
175
+ let gitPollTimer: ReturnType<typeof setInterval> | null = null;
176
+ let processScanTimer: ReturnType<typeof setInterval> | null = null;
177
+ let previousProcessPids: string = ""; // JSON-stringified PID set for diff
178
+ const trackedPgids = new Set<number>(); // PGIDs captured during bash tool calls
179
+ let lastGitBranch: string | undefined;
180
+ let lastGitPrNumber: number | undefined;
181
+ let lastSessionName: string | undefined;
182
+ let cachedHasUI: boolean | undefined = prev.hasUI;
183
+ let cachedModelRegistry: any | undefined = prev.modelRegistry;
184
+ let cachedCtx: any | undefined = prev.ctx;
185
+ let lastModel: string | undefined;
186
+ let lastThinkingLevel: string | undefined;
187
+ let promptBus: PromptBus | undefined;
188
+
189
+ /** Wrap a callback so errors log instead of crashing the host pi agent. */
190
+ function safe<T extends (...args: any[]) => any>(fn: T): T {
191
+ return ((...args: any[]) => {
192
+ try {
193
+ const result = fn(...args);
194
+ if (result && typeof result.catch === "function") {
195
+ return result.catch((err: unknown) => {
196
+ console.error("[dashboard]", err);
197
+ });
198
+ }
199
+ return result;
200
+ } catch (err) {
201
+ console.error("[dashboard]", err);
202
+ }
203
+ }) as T;
204
+ }
205
+
206
+ // Load config to determine WebSocket URL
207
+ ensureConfig();
208
+ const config = loadConfig();
209
+ const dashboardUrl = process.env.PI_DASHBOARD_URL ?? `ws://localhost:${config.piPort}`;
210
+
211
+ const connection = new ConnectionManager({
212
+ url: dashboardUrl,
213
+ onMessage: safe(async (data: unknown) => {
214
+ if (!isActive()) return; // Stale listener guard
215
+ const msg = data as ServerToExtensionMessage;
216
+ // Legacy extension_ui_response removed — now handled by prompt_response → promptBus.respond()
217
+ // Reload auth credentials when dashboard notifies of changes
218
+ if (msg.type === "credentials_updated") {
219
+ try {
220
+ // Hot-reload providers.json diff BEFORE refreshing the registry,
221
+ // so any newly added providers are registered before getAvailable() runs.
222
+ const diff = await reloadProviders(pi).catch((err) => {
223
+ console.error("[dashboard] reloadProviders failed:", err);
224
+ return { added: [], removed: [], changed: [] };
225
+ });
226
+ if (diff.added.length || diff.removed.length || diff.changed.length) {
227
+ console.log(
228
+ `[dashboard] hot-reloaded providers: added=${JSON.stringify(diff.added)} removed=${JSON.stringify(diff.removed)} changed=${JSON.stringify(diff.changed)}`,
229
+ );
230
+ }
231
+ cachedModelRegistry?.authStorage?.reload?.();
232
+ cachedModelRegistry?.refresh?.();
233
+ } catch (err) { console.error("[dashboard] credentials reload failed:", err); }
234
+ // Push updated models list to dashboard client
235
+ if (cachedModelRegistry && sessionReady) {
236
+ try {
237
+ const models = cachedModelRegistry.getAvailable().map((m: any) => ({
238
+ provider: m.provider,
239
+ id: m.id,
240
+ }));
241
+ connection.send({ type: "models_list", sessionId, models });
242
+ } catch (err) { console.error("[dashboard] models_list push failed:", err); }
243
+ }
244
+ return;
245
+ }
246
+ // Route flow management actions from dashboard buttons
247
+ if (msg.type === "flow_management" && pi.events) {
248
+ if (msg.action === "run") {
249
+ pi.events.emit("flow:run", { flowName: msg.flowName, task: msg.task || undefined });
250
+ } else if (msg.action === "new") {
251
+ pi.events.emit("flows:new-request", { description: msg.description || "" });
252
+ } else if (msg.action === "edit") {
253
+ const editFlows = getFlowsList() as Array<{ name: string; source?: string }>;
254
+ const editMatch = editFlows.find(f => f.name === msg.flowName);
255
+ const resolvedPath = editMatch?.source || "";
256
+ if (!resolvedPath) {
257
+ console.error(`[dashboard] flow_management edit: could not resolve path for "${msg.flowName}" (${editFlows.length} flows)`);
258
+ }
259
+ pi.events.emit("flows:edit-request", { flowName: msg.flowName || "", flowPath: resolvedPath, modificationRequest: msg.description || "" });
260
+ } else if (msg.action === "delete") {
261
+ // Dashboard already confirmed upfront — delete directly
262
+ pi.events.emit("flow:delete-request", { flowName: msg.flowName });
263
+ pi.events.emit("flow:notify", { message: `Flow "${msg.flowName}" deleted.`, level: "info" });
264
+ }
265
+ return;
266
+ }
267
+ // Route role management from dashboard
268
+ if (msg.type === "role_set" && pi.events) {
269
+ const data: any = { role: (msg as any).role, modelId: (msg as any).modelId };
270
+ pi.events.emit("flow:role-set", data);
271
+ if (data.success) {
272
+ const rolesData: any = {};
273
+ pi.events.emit("flow:role-get-all", rolesData);
274
+ connection.send({
275
+ type: "roles_list",
276
+ sessionId,
277
+ roles: rolesData.roles ?? {},
278
+ presets: rolesData.presets ?? [],
279
+ activePreset: rolesData.activePreset ?? null,
280
+ });
281
+ }
282
+ return;
283
+ }
284
+ if (msg.type === "role_preset_load" && pi.events) {
285
+ const data: any = { name: (msg as any).presetName };
286
+ pi.events.emit("flow:role-preset-load", data);
287
+ if (data.success) {
288
+ const rolesData: any = {};
289
+ pi.events.emit("flow:role-get-all", rolesData);
290
+ connection.send({
291
+ type: "roles_list",
292
+ sessionId,
293
+ roles: rolesData.roles ?? {},
294
+ presets: rolesData.presets ?? [],
295
+ activePreset: rolesData.activePreset ?? null,
296
+ });
297
+ }
298
+ return;
299
+ }
300
+ if (msg.type === "role_preset_save" && pi.events) {
301
+ const data: any = { name: (msg as any).presetName };
302
+ pi.events.emit("flow:role-preset-save", data);
303
+ if (data.success) {
304
+ const rolesData: any = {};
305
+ pi.events.emit("flow:role-get-all", rolesData);
306
+ connection.send({
307
+ type: "roles_list",
308
+ sessionId,
309
+ roles: rolesData.roles ?? {},
310
+ presets: rolesData.presets ?? [],
311
+ activePreset: rolesData.activePreset ?? null,
312
+ });
313
+ }
314
+ return;
315
+ }
316
+ if (msg.type === "role_preset_delete" && pi.events) {
317
+ const data: any = { name: (msg as any).presetName };
318
+ pi.events.emit("flow:role-preset-delete", data);
319
+ if (data.success) {
320
+ const rolesData: any = {};
321
+ pi.events.emit("flow:role-get-all", rolesData);
322
+ connection.send({
323
+ type: "roles_list",
324
+ sessionId,
325
+ roles: rolesData.roles ?? {},
326
+ presets: rolesData.presets ?? [],
327
+ activePreset: rolesData.activePreset ?? null,
328
+ });
329
+ }
330
+ return;
331
+ }
332
+ if (msg.type === "request_roles" && pi.events) {
333
+ const rolesData: any = {};
334
+ pi.events.emit("flow:role-get-all", rolesData);
335
+ connection.send({
336
+ type: "roles_list",
337
+ sessionId,
338
+ roles: rolesData.roles ?? {},
339
+ presets: rolesData.presets ?? [],
340
+ activePreset: rolesData.activePreset ?? null,
341
+ });
342
+ return;
343
+ }
344
+ // Route PromptBus responses from dashboard client
345
+ if (msg.type === "prompt_response" && promptBus) {
346
+ promptBus.respond({
347
+ id: (msg as any).promptId,
348
+ answer: (msg as any).answer,
349
+ cancelled: (msg as any).cancelled,
350
+ source: (msg as any).source ?? "dashboard-default",
351
+ });
352
+ return;
353
+ }
354
+ // Legacy architect_prompt_response routing REMOVED.
355
+ // Previously routed to flow:prompt-response + cancelAllPending().
356
+ // Now handled by PromptBus: dashboard sends prompt_response,
357
+ // bus calls respond(), adapters get onResponse() for cross-cancellation.
358
+ // Route flow control messages to pi-flows via pi.events
359
+ if (msg.type === "flow_control" && pi.events) {
360
+ if (msg.action === "abort") {
361
+ pi.events.emit("flow:abort", {});
362
+ // Also abort architect if running (mutually exclusive with flow execution;
363
+ // the irrelevant emit is a no-op due to guard checks on both listeners)
364
+ pi.events.emit("flow:architect-abort", {});
365
+ } else if (msg.action === "toggle_autonomous") {
366
+ pi.events.emit("flow:toggle-autonomous", {});
367
+ } else if (msg.action === "dismiss_summary") {
368
+ pi.events.emit("flow:summary-dismissed", {});
369
+ }
370
+ return;
371
+ }
372
+ const response = await commandHandler.handle(msg);
373
+ if (response) connection.send(response);
374
+ // Immediately send model/thinking update after handling set_thinking_level
375
+ if (msg.type === "set_thinking_level") {
376
+ // Small delay to let pi process the level change
377
+ setTimeout(() => sendModelUpdateIfChanged(), 50);
378
+ }
379
+ }),
380
+ onReconnect: safe(() => {
381
+ if (!isActive()) return; // Stale listener guard
382
+ sendStateSync();
383
+ replaySessionEntries();
384
+ // Re-send pending PromptBus requests so dashboard dialogs survive browser refresh.
385
+ // Synchronous within this tick to prevent TUI respond() from interleaving.
386
+ // Client-side dedup by requestId prevents double-rendering.
387
+ if (promptBus) {
388
+ for (const { request, component, placement } of promptBus.getPendingRequests()) {
389
+ connection.send({
390
+ type: "prompt_request" as any,
391
+ sessionId,
392
+ promptId: request.id,
393
+ prompt: {
394
+ type: request.type,
395
+ question: request.question,
396
+ options: request.options,
397
+ defaultValue: request.defaultValue,
398
+ pipeline: request.pipeline,
399
+ metadata: request.metadata,
400
+ },
401
+ component,
402
+ placement,
403
+ });
404
+ }
405
+ }
406
+ connection.send({ type: "replay_complete", sessionId });
407
+ // If agent is mid-turn, send synthetic agent_start so server sets status to "streaming"
408
+ if (getBridgeState().isAgentStreaming) {
409
+ connection.send(mapEventToProtocol(sessionId, { type: "agent_start" }));
410
+ }
411
+ }),
412
+ });
413
+
414
+ // Track connection so future bridge incarnations can disconnect it
415
+ getBridgeState().connections!.push(connection);
416
+
417
+ const commandHandler = createCommandHandler(pi, () => sessionId, {
418
+ getModelRegistry: () => cachedModelRegistry,
419
+ setThinkingLevel: (level: string) => (pi as any).setThinkingLevel?.(level),
420
+ getThinkingLevel: () => (pi as any).getThinkingLevel?.(),
421
+ setModel: async (provider: string, modelId: string) => {
422
+ const registry = cachedModelRegistry;
423
+ if (!registry) return;
424
+ const model = registry.find(provider, modelId);
425
+ if (!model) return;
426
+ try {
427
+ await (pi as any).setModel(model);
428
+ } catch {
429
+ return;
430
+ }
431
+ // model_select event updates cachedCtx; small delay lets it propagate
432
+ setTimeout(() => sendModelUpdateIfChanged(), 50);
433
+ },
434
+ shutdown: () => {
435
+ if (cachedCtx?.shutdown) {
436
+ cachedCtx.shutdown();
437
+ }
438
+ // Safety net: force exit after a short delay in case ctx.shutdown()
439
+ // doesn't terminate (e.g. in RPC mode headless sessions)
440
+ setTimeout(() => process.exit(0), 500);
441
+ },
442
+ abort: () => {
443
+ if (cachedCtx?.abort) {
444
+ cachedCtx.abort();
445
+ }
446
+ },
447
+ eventSink: (msg) => connection.send(msg),
448
+ compact: (opts) => {
449
+ if (cachedCtx?.compact) {
450
+ cachedCtx.compact(opts);
451
+ }
452
+ },
453
+ reload: () => {
454
+ const reloadFn = (globalThis as any)[RELOAD_KEY] as (() => Promise<void>) | undefined;
455
+ if (reloadFn) {
456
+ reloadFn().catch((err: any) => {
457
+ console.error("[dashboard] reload failed:", err);
458
+ });
459
+ } else {
460
+ console.error("[dashboard] reload not available — type /__dashboard_reload in pi TUI once to bootstrap");
461
+ }
462
+ },
463
+ spawnNew: () => {
464
+ connection.send({ type: "spawn_new_session", sessionId, cwd: process.cwd() });
465
+ },
466
+ sessionPrompt: (text) => {
467
+ // Route slash commands: management events, flow:run, then fallback
468
+ if (text.startsWith("/") && pi.events) {
469
+ const cmdText = text.slice(1);
470
+ const spaceIdx = cmdText.indexOf(" ");
471
+ const cmdName = spaceIdx === -1 ? cmdText : cmdText.slice(0, spaceIdx);
472
+ const cmdArgs = spaceIdx === -1 ? "" : cmdText.slice(spaceIdx + 1);
473
+
474
+ // Flow management commands from buttons use flow_management message type.
475
+ // Typed /flows:new, /flows:edit, /flows:delete in chat input fall through
476
+ // to the slash command handler below, which invokes pi's command system
477
+ // via pi.sendUserMessage (with ui-proxy handling ctx.ui calls).
478
+
479
+ // Check if it's a user-defined flow via flow:list-flows
480
+ const flowsList = getFlowsList();
481
+ if (flowsList.some(f => f.name === cmdName)) {
482
+ pi.events.emit("flow:run", { flowName: cmdName, task: cmdArgs.trim() || undefined });
483
+ return;
484
+ }
485
+ }
486
+ // Fallback: send as user message (template-expanded).
487
+ // Uses deliverAs:followUp so it queues properly when agent is streaming.
488
+ // expandPromptTemplateFromDisk handles skill commands (/skill:xxx) and
489
+ // prompt templates by reading the file content from disk.
490
+ const expanded = expandPromptTemplateFromDisk(text, process.cwd(), pi);
491
+ (pi.sendUserMessage as any)(expanded, { deliverAs: "followUp" });
492
+ },
493
+ });
494
+
495
+ // Reload support: extension events only provide ExtensionContext (no reload).
496
+ // ExtensionCommandContext (with reload()) is only available in command handlers.
497
+ // We register __dashboard_reload command; invoking /__dashboard_reload from pi TUI
498
+ // captures ctx.reload(). After first capture, dashboard-triggered reloads work.
499
+ // The captured fn is stored in globalThis to survive module reloads.
500
+ const RELOAD_KEY = "__pi_dashboard_reload_fn__";
501
+
502
+ pi.registerCommand("__dashboard_reload", {
503
+ handler: async (_args: string, ctx: any) => {
504
+ if (ctx?.reload) {
505
+ (globalThis as any)[RELOAD_KEY] = () => ctx.reload();
506
+ await ctx.reload();
507
+ }
508
+ },
509
+ });
510
+
511
+ /** Sync local variables into BridgeContext for extracted module calls */
512
+ function syncBc(): BridgeContext {
513
+ return {
514
+ pi, connection, sessionId,
515
+ cachedCtx, cachedModelRegistry, cachedHasUI,
516
+ lastModel, lastThinkingLevel,
517
+ lastSessionFile, lastSessionDir, lastFirstMessage,
518
+ lastGitBranch, lastGitPrNumber, lastSessionName,
519
+ };
520
+ }
521
+ /** Sync BridgeContext mutations back to local variables */
522
+ function applyBc(bc: BridgeContext): void {
523
+ sessionId = bc.sessionId;
524
+ cachedCtx = bc.cachedCtx;
525
+ cachedModelRegistry = bc.cachedModelRegistry;
526
+ cachedHasUI = bc.cachedHasUI;
527
+ lastModel = bc.lastModel;
528
+ lastThinkingLevel = bc.lastThinkingLevel;
529
+ lastSessionFile = bc.lastSessionFile;
530
+ lastSessionDir = bc.lastSessionDir;
531
+ lastFirstMessage = bc.lastFirstMessage;
532
+ lastGitBranch = bc.lastGitBranch;
533
+ lastGitPrNumber = bc.lastGitPrNumber;
534
+ lastSessionName = bc.lastSessionName;
535
+ }
536
+
537
+ // Local wrappers that sync bc around extracted module calls
538
+ function sendStateSync() { const bc = syncBc(); _sendStateSync(bc, getFlowsList); applyBc(bc); }
539
+ function replaySessionEntries() { _replaySessionEntries(syncBc()); }
540
+ function sendModelUpdateIfChanged() { const bc = syncBc(); _sendModelUpdateIfChanged(bc); applyBc(bc); }
541
+ function sendSessionNameIfChanged() { const bc = syncBc(); _sendSessionNameIfChanged(bc); applyBc(bc); }
542
+ function sendGitInfoIfChanged(cwd: string) { const bc = syncBc(); _sendGitInfoIfChanged(bc, cwd); applyBc(bc); }
543
+
544
+ // Forward all pi core events to the dashboard.
545
+ // Events with special enrichment logic:
546
+ const enrichedEventTypes = [
547
+ "agent_start",
548
+ "agent_end",
549
+ "turn_start",
550
+ "turn_end",
551
+ "message_start",
552
+ "message_update",
553
+ "message_end",
554
+ "tool_execution_start",
555
+ "tool_execution_update",
556
+ "tool_execution_end",
557
+ "session_compact",
558
+ "model_select",
559
+ ] as const;
560
+ // Pass-through events: forwarded as-is with no special handling.
561
+ // Unrecognized types render as expandable JSON cards in the dashboard.
562
+ const passThroughEventTypes = [
563
+ "tool_call",
564
+ "tool_result",
565
+ "user_bash",
566
+ "input",
567
+ "before_agent_start",
568
+ "resources_discover",
569
+ "session_before_switch",
570
+ "session_before_fork",
571
+ "session_before_compact",
572
+ "session_before_tree",
573
+ "session_tree",
574
+ ] as const;
575
+ // Excluded from subscription (not forwarded):
576
+ // - `context`: carries full message arrays (very large)
577
+ // - `before_provider_request`: carries raw API payloads (very large)
578
+ // - `session_start`: dedicated handler → session_register protocol message
579
+ // - session change (new/fork/resume): handled inside session_start via event.reason
580
+ // - `session_shutdown`: dedicated handler → disconnect/cleanup
581
+
582
+ // Unified EventBus rename map for the emit intercept (flow + subagent events)
583
+ const EVENT_BUS_MAP: Record<string, string> = { ...FLOW_EVENT_MAP, ...SUBAGENT_EVENT_MAP };
584
+
585
+ for (const eventType of enrichedEventTypes) {
586
+ pi.on(eventType as any, safe(async (event: any, ctx: any) => {
587
+ // Bail out if a newer bridge instance has taken over
588
+ if (!isActive()) return;
589
+ // Always keep latest context for abort/shutdown
590
+ cachedCtx = ctx;
591
+ // Don't send events before session_start has established the correct session ID
592
+ if (!sessionReady) return;
593
+ // Track agent streaming state (survives reconnect/reload)
594
+ if (eventType === "agent_start") getBridgeState().isAgentStreaming = true;
595
+ if (eventType === "agent_end") getBridgeState().isAgentStreaming = false;
596
+ // For model_select, enrich the event data with thinkingLevel
597
+ if (eventType === "model_select") {
598
+ const enriched = { ...event, thinkingLevel: (pi as any).getThinkingLevel?.() };
599
+ const msg = mapEventToProtocol(sessionId, enriched);
600
+ connection.send(msg);
601
+ return;
602
+ }
603
+
604
+ // For turn_end, enrich with contextUsage (pi-only API) so server can extract stats
605
+ if (eventType === "turn_end") {
606
+ const contextUsage = ctx.getContextUsage?.();
607
+ if (contextUsage) {
608
+ const enriched = { ...event, contextUsage };
609
+ const msg = mapEventToProtocol(sessionId, enriched);
610
+ connection.send(msg);
611
+ return;
612
+ }
613
+ }
614
+
615
+ // For message_start, enrich with entryId immediately (current leaf)
616
+ if (eventType === "message_start") {
617
+ const entryId = ctx.sessionManager?.getLeafId?.();
618
+ if (entryId) {
619
+ const enriched = { ...event, entryId };
620
+ const msg = mapEventToProtocol(sessionId, enriched);
621
+ connection.send(msg);
622
+ return;
623
+ }
624
+ }
625
+
626
+ // For message_end, defer getLeafId() so it runs after pi core persists the entry.
627
+ // Pi core calls _emit (which invokes this handler) BEFORE appendMessage (which updates leafId).
628
+ // Since _emit doesn't await async handlers, yielding via queueMicrotask lets appendMessage
629
+ // run first, so getLeafId() returns the correct entry ID for the just-persisted message.
630
+ if (eventType === "message_end") {
631
+ await new Promise<void>(resolve => queueMicrotask(resolve));
632
+ const entryId = ctx.sessionManager?.getLeafId?.();
633
+ if (entryId) {
634
+ const enriched = { ...event, entryId };
635
+ const msg = mapEventToProtocol(sessionId, enriched);
636
+ connection.send(msg);
637
+ return;
638
+ }
639
+ }
640
+
641
+ const msg = mapEventToProtocol(sessionId, event);
642
+ connection.send(msg);
643
+ }));
644
+ }
645
+
646
+ // Pass-through events: forward with no enrichment
647
+ for (const eventType of passThroughEventTypes) {
648
+ pi.on(eventType as any, safe(async (event: any, ctx: any) => {
649
+ if (!isActive()) return;
650
+ cachedCtx = ctx;
651
+ if (!sessionReady) return;
652
+ const msg = mapEventToProtocol(sessionId, event);
653
+ connection.send(msg);
654
+ }));
655
+ }
656
+
657
+ // EventBus catch-all: intercept pi.events.emit to forward all EventBus
658
+ // traffic (flow events, subagent events, custom extension events).
659
+ // Known channels get renamed via EVENT_BUS_MAP; unknown channels use the
660
+ // channel name directly as the eventType.
661
+ let origEventsEmit: ((channel: string, data: unknown) => void) | undefined;
662
+ if (pi.events) {
663
+ origEventsEmit = pi.events.emit.bind(pi.events);
664
+ pi.events.emit = (channel: string, data: unknown) => {
665
+ if (sessionReady && isActive()) {
666
+ try {
667
+ const eventType = EVENT_BUS_MAP[channel] ?? channel;
668
+ const eventData = (data && typeof data === "object" ? data : {}) as Record<string, unknown>;
669
+ connection.send({
670
+ type: "event_forward",
671
+ sessionId,
672
+ event: { eventType, timestamp: Date.now(), data: eventData },
673
+ });
674
+ } catch { /* forwarding failure must never break the original emit */ }
675
+ }
676
+ origEventsEmit!(channel, data);
677
+ };
678
+ }
679
+
680
+ pi.on("session_start", safe(async (_event: any, ctx: any) => {
681
+
682
+ // Bail out if a newer bridge instance has taken over
683
+ if (!isActive()) return;
684
+ const newSessionId = ctx.sessionManager.getSessionId();
685
+
686
+ // On session switch/fork (0.65.0+: event.reason replaces session_switch/session_fork events),
687
+ // unregister the old session before re-registering the new one.
688
+ const reason = _event?.reason;
689
+ if ((reason === "new" || reason === "fork" || reason === "resume") && sessionId && sessionId !== newSessionId) {
690
+ handleSessionChange(ctx);
691
+ }
692
+
693
+ cachedHasUI = ctx.hasUI;
694
+ cachedCtx = ctx;
695
+ sessionId = newSessionId;
696
+
697
+ // Register ask_user at runtime (not at load time) to avoid static
698
+ // tool-name conflicts with other extensions like pi-flows.
699
+ registerAskUserTool(pi);
700
+
701
+ // Extract session file/dir early — needed for source detection and UI proxy
702
+ const sessionFile = ctx.sessionManager.getSessionFile?.() ?? undefined;
703
+ const sessionDir = ctx.sessionManager.getSessionDir?.() ?? undefined;
704
+ lastSessionFile = sessionFile;
705
+ lastSessionDir = sessionDir;
706
+
707
+ // ── PromptBus setup ──
708
+ // Create bus with dashboard connection wiring.
709
+ // Replaces the old ui-proxy race pattern.
710
+ promptBus = new PromptBus({
711
+ onDashboardRequest: (prompt, component, placement) => {
712
+ connection.send({
713
+ type: "prompt_request" as any,
714
+ sessionId,
715
+ promptId: prompt.id,
716
+ prompt: {
717
+ question: prompt.question,
718
+ type: prompt.type,
719
+ options: prompt.options,
720
+ defaultValue: prompt.defaultValue,
721
+ pipeline: prompt.pipeline,
722
+ metadata: prompt.metadata,
723
+ },
724
+ component,
725
+ placement,
726
+ });
727
+ },
728
+ onDashboardDismiss: (id) => {
729
+ connection.send({ type: "prompt_dismiss" as any, sessionId, promptId: id });
730
+ },
731
+ onDashboardCancel: (id) => {
732
+ connection.send({ type: "prompt_cancel" as any, sessionId, promptId: id });
733
+ },
734
+ });
735
+
736
+ // Register built-in default adapter (always present, works without pi-flows)
737
+ promptBus.registerAdapter(new DashboardDefaultAdapter());
738
+
739
+ // Capture original ctx.ui method references BEFORE patching
740
+ const originalNotify = ctx.ui.notify?.bind(ctx.ui);
741
+ const originals = {
742
+ select: ctx.ui.select?.bind(ctx.ui) as ((q: string, opts: string[], extra?: any) => Promise<string | undefined>) | undefined,
743
+ input: ctx.ui.input?.bind(ctx.ui) as ((q: string, placeholder?: string, extra?: any) => Promise<string | undefined>) | undefined,
744
+ confirm: ctx.ui.confirm?.bind(ctx.ui) as ((q: string, msg: string, extra?: any) => Promise<boolean>) | undefined,
745
+ editor: ctx.ui.editor?.bind(ctx.ui) as ((q: string, prefill?: string, extra?: any) => Promise<string | undefined>) | undefined,
746
+ };
747
+
748
+ // Register TUI adapter — presents prompts in the terminal using original
749
+ // (unpatched) ctx.ui methods. Must be registered BEFORE patching ctx.ui.
750
+ if (ctx.hasUI) {
751
+ const activeControllers = new Map<string, AbortController>();
752
+ const bus = promptBus;
753
+
754
+ bus.registerAdapter({
755
+ name: "tui",
756
+
757
+ onRequest(prompt: any) {
758
+ const ac = new AbortController();
759
+ activeControllers.set(prompt.id, ac);
760
+
761
+ const present = async () => {
762
+ try {
763
+ let answer: string | boolean | undefined;
764
+
765
+ if (prompt.type === "select" && prompt.options && originals.select) {
766
+ answer = await originals.select(prompt.question, prompt.options, { signal: ac.signal });
767
+ } else if (prompt.type === "input" && originals.input) {
768
+ answer = await originals.input(prompt.question, prompt.defaultValue || "", { signal: ac.signal });
769
+ } else if (prompt.type === "confirm" && originals.confirm) {
770
+ answer = await originals.confirm(prompt.question, "", { signal: ac.signal });
771
+ } else if (prompt.type === "editor" && originals.editor) {
772
+ answer = await originals.editor(prompt.question, prompt.defaultValue || "", { signal: ac.signal });
773
+ } else {
774
+ return;
775
+ }
776
+
777
+ if (!ac.signal.aborted) {
778
+ const answerStr = typeof answer === "boolean" ? (answer ? "true" : "false") : answer;
779
+ bus.respond({
780
+ id: prompt.id,
781
+ answer: answerStr ?? undefined,
782
+ cancelled: answerStr == null,
783
+ source: "tui",
784
+ });
785
+ }
786
+ } catch {
787
+ if (!ac.signal.aborted) {
788
+ bus.respond({ id: prompt.id, cancelled: true, source: "tui" });
789
+ }
790
+ } finally {
791
+ activeControllers.delete(prompt.id);
792
+ }
793
+ };
794
+
795
+ present();
796
+ return {}; // Claim without component (TUI-only)
797
+ },
798
+
799
+ onResponse(response: any) {
800
+ if (response.source !== "tui") {
801
+ const ac = activeControllers.get(response.id);
802
+ if (ac) {
803
+ ac.abort();
804
+ activeControllers.delete(response.id);
805
+ }
806
+ }
807
+ },
808
+
809
+ onCancel(id: string) {
810
+ const ac = activeControllers.get(id);
811
+ if (ac) {
812
+ ac.abort();
813
+ activeControllers.delete(id);
814
+ }
815
+ },
816
+ });
817
+ }
818
+
819
+ // Replace ctx.ui dialog methods with PromptBus wrappers.
820
+ // All extension commands that call ctx.ui.select/input/confirm/editor
821
+ // now route through the bus, which distributes to all registered adapters.
822
+ {
823
+ const bus = promptBus;
824
+ (ctx.ui as any).select = (title: string, options: string[], opts?: any) =>
825
+ bus.request({ pipeline: "command", type: "select", question: title, options, metadata: opts?.message ? { message: opts.message } : undefined })
826
+ .then(r => r.cancelled ? undefined : r.answer);
827
+
828
+ (ctx.ui as any).input = (title: string, placeholder?: string, opts?: any) =>
829
+ bus.request({ pipeline: "command", type: "input", question: title, defaultValue: placeholder, metadata: opts?.message ? { message: opts.message } : undefined })
830
+ .then(r => r.cancelled ? undefined : r.answer);
831
+
832
+ (ctx.ui as any).confirm = (title: string, message?: string, opts?: any) =>
833
+ bus.request({ pipeline: "command", type: "confirm", question: title, metadata: (message || opts?.message) ? { message: message || opts?.message } : undefined })
834
+ .then(r => !r.cancelled && r.answer === "true");
835
+
836
+ (ctx.ui as any).editor = (title: string, prefill?: string, opts?: any) =>
837
+ bus.request({ pipeline: "command", type: "editor", question: title, defaultValue: prefill, metadata: opts?.message ? { message: opts.message } : undefined })
838
+ .then(r => r.cancelled ? undefined : r.answer);
839
+
840
+ // Notify is fire-and-forget: call original + forward to dashboard
841
+ (ctx.ui as any).notify = (message: string, level?: string) => {
842
+ originalNotify?.(message, level);
843
+ connection.send({
844
+ type: "prompt_request" as any,
845
+ sessionId,
846
+ promptId: crypto.randomUUID(),
847
+ prompt: { question: message, type: "notify" },
848
+ component: { type: "notify", props: { message, level } },
849
+ placement: "inline",
850
+ });
851
+ };
852
+ }
853
+
854
+ // Listen for adapter registrations from other extensions (e.g. pi-flows)
855
+ if (pi.events) {
856
+ pi.events.on("prompt:register-adapter", (adapter: any) => {
857
+ if (promptBus && adapter && typeof adapter.name === "string") {
858
+ promptBus.registerAdapter(adapter);
859
+ // Inject respond/cancel functions so cross-package adapters can talk back
860
+ if (typeof adapter.setRespond === "function") {
861
+ adapter.setRespond((response: any) => promptBus!.respond(response));
862
+ }
863
+ if (typeof adapter.setCancel === "function") {
864
+ adapter.setCancel((id: string) => promptBus!.cancel(id));
865
+ }
866
+ }
867
+ });
868
+
869
+ // Expose bus request function for pi-flows to use via emitPromptAndAwait
870
+ pi.events.emit("prompt:set-bus-request", {
871
+ request: (options: any) => promptBus!.request(options),
872
+ });
873
+ }
874
+
875
+ // Connect first, then auto-start if needed.
876
+ // session_register must be buffered before any event_forward messages.
877
+ connection.connect();
878
+
879
+ // Extract first message (sessionFile/sessionDir already extracted above)
880
+ const firstMessage = extractFirstMessage(ctx);
881
+ lastFirstMessage = firstMessage;
882
+
883
+ // Register session with initial model/thinkingLevel
884
+ lastSessionName = pi.getSessionName() ?? "";
885
+ const initialModel = getCurrentModelString(syncBc());
886
+ const initialThinkingLevel = (pi as any).getThinkingLevel?.() ?? undefined;
887
+ lastModel = initialModel;
888
+ lastThinkingLevel = initialThinkingLevel;
889
+
890
+ // Include eventCount so server can skip event wipe on reconnect
891
+ let eventCount: number | undefined;
892
+ try {
893
+ const entries = ctx.sessionManager?.getBranch?.();
894
+ if (entries) eventCount = entries.length;
895
+ } catch { /* ignore */ }
896
+
897
+ connection.send({
898
+ type: "session_register",
899
+ sessionId,
900
+ cwd: ctx.cwd,
901
+ name: lastSessionName || undefined,
902
+ source: detectSessionSource(cachedHasUI, sessionFile),
903
+ model: initialModel,
904
+ thinkingLevel: initialThinkingLevel,
905
+ sessionFile,
906
+ sessionDir,
907
+ firstMessage,
908
+ eventCount,
909
+ });
910
+
911
+ // Allow event forwarding now that session_register is buffered
912
+ sessionReady = true;
913
+
914
+ // Replay full session history so the dashboard has all messages
915
+ replaySessionEntries();
916
+ connection.send({ type: "replay_complete", sessionId });
917
+ // If agent is mid-turn (e.g. reload during streaming), send synthetic agent_start
918
+ if (getBridgeState().isAgentStreaming) {
919
+ connection.send(mapEventToProtocol(sessionId, { type: "agent_start" }));
920
+ }
921
+
922
+ // Send initial commands list
923
+ const commands = filterHiddenCommands(pi.getCommands());
924
+ connection.send({
925
+ type: "commands_list",
926
+ sessionId,
927
+ commands,
928
+ });
929
+
930
+ // Send initial flows list
931
+ sendFlowsList();
932
+
933
+ // Send available models
934
+ cachedModelRegistry = (ctx as any).modelRegistry;
935
+ if (cachedModelRegistry) {
936
+ try {
937
+ const models = cachedModelRegistry.getAvailable().map((m: any) => ({
938
+ provider: m.provider,
939
+ id: m.id,
940
+ }));
941
+ connection.send({ type: "models_list", sessionId, models });
942
+ } catch { /* modelRegistry not available */ }
943
+ }
944
+
945
+ // Apply default model on new sessions only (not reload/resume/fork)
946
+ if (_event?.reason === "startup" && cachedModelRegistry) {
947
+ pendingDefaultModel = applyDefaultModel();
948
+ }
949
+
950
+ // Send initial roles
951
+ if (pi.events) {
952
+ const rolesData: any = {};
953
+ pi.events.emit("flow:role-get-all", rolesData);
954
+ if (rolesData.roles) {
955
+ connection.send({
956
+ type: "roles_list",
957
+ sessionId,
958
+ roles: rolesData.roles ?? {},
959
+ presets: rolesData.presets ?? [],
960
+ activePreset: rolesData.activePreset ?? null,
961
+ });
962
+ }
963
+ }
964
+
965
+ // Discover or auto-start server (non-blocking — connection will reconnect)
966
+ //
967
+ // When a real launchServer() is about to run (not on mDNS/health-check
968
+ // paths), mount an animated TUI widget above the editor using pi-tui's
969
+ // Loader (a real Component, self-animating at 80ms, like pi-flows'
970
+ // architect-widget). The previous implementation used
971
+ // ctx.ui.setStatus(...) which only writes a footer string and relies on
972
+ // the TUI render loop being ticked elsewhere — on the cold-start path
973
+ // nothing else requests renders, so the spinner never animated and often
974
+ // never appeared. setWidget(key, factory, {placement:"aboveEditor"}) gives
975
+ // us a managed component that owns its own render loop and is always
976
+ // visible while the launch is in flight.
977
+ let spinnerTimer: NodeJS.Timeout | null = null;
978
+ let spinnerStart = 0;
979
+ let activeLoader: Loader | null = null;
980
+ const stopSpinner = () => {
981
+ if (spinnerTimer) {
982
+ clearInterval(spinnerTimer);
983
+ spinnerTimer = null;
984
+ }
985
+ activeLoader = null;
986
+ ctx.ui.setWidget("pi-dashboard-launch", undefined);
987
+ };
988
+ autoStartServer(config, {
989
+ discoverDashboard,
990
+ isDashboardRunning,
991
+ launchServer,
992
+ notify: (msg, level) => ctx.ui.notify(msg, level),
993
+ onLaunchStart: () => {
994
+ spinnerStart = Date.now();
995
+ const buildMessage = () => {
996
+ const elapsed = Math.floor((Date.now() - spinnerStart) / 1000);
997
+ return `starting dashboard server … (${elapsed}s)`;
998
+ };
999
+ ctx.ui.setWidget(
1000
+ "pi-dashboard-launch",
1001
+ (tui: unknown, theme: { fg: (role: string, s: string) => string }) => {
1002
+ const loader = new Loader(
1003
+ tui as ConstructorParameters<typeof Loader>[0],
1004
+ (s: string) => theme.fg("accent", s),
1005
+ (s: string) => theme.fg("muted", s),
1006
+ buildMessage(),
1007
+ );
1008
+ activeLoader = loader;
1009
+ // Loader has stop() but no dispose(); wire dispose so that
1010
+ // setExtensionWidget's teardown stops the 80ms animation interval.
1011
+ (loader as Loader & { dispose?: () => void }).dispose = () => loader.stop();
1012
+ return loader;
1013
+ },
1014
+ { placement: "aboveEditor" },
1015
+ );
1016
+ // Refresh the elapsed-seconds label every second. Frame animation is
1017
+ // driven by the Loader's own 80ms interval.
1018
+ spinnerTimer = setInterval(() => {
1019
+ activeLoader?.setMessage(buildMessage());
1020
+ }, 1000);
1021
+ },
1022
+ onLaunchEnd: () => {
1023
+ stopSpinner();
1024
+ },
1025
+ }).then((result) => {
1026
+ stopSpinner(); // safety net — covers onLaunchEnd not firing
1027
+ if (result.server && result.server.piPort !== config.piPort) {
1028
+ // Server found on a different piPort than configured — update connection URL
1029
+ connection.updateUrl(`ws://${result.server.host === 'localhost' ? 'localhost' : result.server.host}:${result.server.piPort}`);
1030
+ }
1031
+ }).catch(() => { stopSpinner(); });
1032
+
1033
+ // Send initial git info
1034
+ sendGitInfoIfChanged(ctx.cwd);
1035
+
1036
+ // Start metrics monitor and heartbeat
1037
+ startMetricsMonitor();
1038
+ heartbeatTimer = setInterval(() => {
1039
+ if (!isActive()) return;
1040
+ connection.send({
1041
+ type: "session_heartbeat",
1042
+ sessionId,
1043
+ metrics: collectMetrics(),
1044
+ });
1045
+ }, HEARTBEAT_INTERVAL);
1046
+ getBridgeState().timers!.push(heartbeatTimer);
1047
+
1048
+ // Start git info + name/model polling
1049
+ gitPollTimer = setInterval(() => {
1050
+ if (!isActive()) return;
1051
+ sendGitInfoIfChanged(ctx.cwd);
1052
+ sendSessionNameIfChanged();
1053
+ sendModelUpdateIfChanged();
1054
+ }, GIT_POLL_INTERVAL);
1055
+ getBridgeState().timers!.push(gitPollTimer);
1056
+
1057
+ // Start process scanner (detect stalled child processes)
1058
+ // Captures new child PGIDs during active bash calls, then checks tracked PGIDs
1059
+ processScanTimer = setInterval(() => {
1060
+ if (!isActive()) return;
1061
+ const processes = scanChildProcesses(process.pid, trackedPgids);
1062
+ const currentPids = JSON.stringify(processes.map((p) => p.pid).sort());
1063
+ if (currentPids !== previousProcessPids) {
1064
+ previousProcessPids = currentPids;
1065
+ connection.send({
1066
+ type: "process_list",
1067
+ sessionId,
1068
+ processes: processes.map((p) => ({ pid: p.pid, pgid: p.pgid, command: p.command, elapsedMs: p.elapsedMs })),
1069
+ });
1070
+ }
1071
+ }, PROCESS_SCAN_INTERVAL);
1072
+ getBridgeState().timers!.push(processScanTimer);
1073
+
1074
+ // Register flow event listeners (pi-flows emits these via pi.events)
1075
+ registerFlowEventListeners(syncBc(), () => sessionReady, getFlowsList);
1076
+ }));
1077
+
1078
+ // Shared handler for session changes (new/fork/resume)
1079
+ function handleSessionChange(ctx: any) {
1080
+ const bc = syncBc();
1081
+ _handleSessionChange(bc, ctx, getFlowsList);
1082
+ applyBc(bc);
1083
+
1084
+ // Restart polling timers
1085
+ if (gitPollTimer) clearInterval(gitPollTimer);
1086
+ gitPollTimer = setInterval(() => {
1087
+ sendGitInfoIfChanged(ctx.cwd);
1088
+ }, GIT_POLL_INTERVAL);
1089
+ }
1090
+
1091
+ // session_switch and session_fork events removed in pi 0.65.0.
1092
+ // Now handled via session_start with event.reason ("new"|"fork"|"resume").
1093
+
1094
+ pi.on("turn_end", safe(async (event: any, ctx: any) => {
1095
+ if (!isActive()) return;
1096
+ cachedCtx = ctx;
1097
+ if (!sessionReady) return;
1098
+
1099
+ // Send firstMessage update after first turn if not previously sent
1100
+ if (!lastFirstMessage) {
1101
+ const firstMsg = extractFirstMessage(ctx);
1102
+ if (firstMsg) {
1103
+ lastFirstMessage = firstMsg;
1104
+ connection.send({
1105
+ type: "first_message_update",
1106
+ sessionId,
1107
+ firstMessage: firstMsg,
1108
+ });
1109
+ }
1110
+ }
1111
+
1112
+ }));
1113
+
1114
+ pi.on("session_shutdown", safe(async () => {
1115
+ if (!isActive()) return;
1116
+ getBridgeState().isAgentStreaming = false;
1117
+ stopMetricsMonitor();
1118
+ if (heartbeatTimer) {
1119
+ clearInterval(heartbeatTimer);
1120
+ heartbeatTimer = null;
1121
+ }
1122
+ if (gitPollTimer) {
1123
+ clearInterval(gitPollTimer);
1124
+ gitPollTimer = null;
1125
+ }
1126
+ connection.send({
1127
+ type: "session_unregister",
1128
+ sessionId,
1129
+ });
1130
+
1131
+ // Give time for the unregister to send
1132
+ await new Promise((resolve) => setTimeout(resolve, 100));
1133
+ connection.disconnect();
1134
+ }));
1135
+
1136
+ // Re-send models list when custom providers finish async discovery
1137
+ onProviderChanged(() => {
1138
+ if (!isActive()) return;
1139
+ if (cachedModelRegistry && sessionReady) {
1140
+ try {
1141
+ const models = cachedModelRegistry.getAvailable().map((m: any) => ({
1142
+ provider: m.provider,
1143
+ id: m.id,
1144
+ }));
1145
+ connection.send({ type: "models_list", sessionId, models });
1146
+ } catch { /* ignore */ }
1147
+
1148
+ // Retry pending default model — custom provider may now have its models
1149
+ if (pendingDefaultModel) {
1150
+ pendingDefaultModel = applyDefaultModel();
1151
+ }
1152
+ }
1153
+ });
1154
+
1155
+ // Register cleanup for /reload — saves state to globalThis and tears down resources
1156
+ const state = getBridgeState();
1157
+ state.cleanup = () => {
1158
+ const s = getBridgeState();
1159
+ s.sessionId = sessionId;
1160
+ s.ctx = cachedCtx;
1161
+ s.modelRegistry = cachedModelRegistry;
1162
+ s.hasUI = cachedHasUI;
1163
+ if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
1164
+ if (gitPollTimer) { clearInterval(gitPollTimer); gitPollTimer = null; }
1165
+
1166
+ // Dev build & restart: rebuild client and stop server before reload
1167
+ if (config.devBuildOnReload) {
1168
+ const __filename = fileURLToPath(import.meta.url);
1169
+ const __dirname = path.dirname(__filename);
1170
+ const packageRoot = path.resolve(__dirname, "..", "..");
1171
+ runDevBuild({ packageRoot, serverPort: config.port });
1172
+ }
1173
+
1174
+ // Restore original pi.events.emit (EventBus catch-all cleanup)
1175
+ if (origEventsEmit && pi.events) {
1176
+ pi.events.emit = origEventsEmit;
1177
+ }
1178
+ connection.disconnect();
1179
+ };
1180
+
1181
+ // Reload is handled by session_start which fires on /reload too
1182
+ }