pi-better-subagents 0.21.1 → 0.22.1

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
@@ -19,6 +19,12 @@ Use `pi-better-subagents` when you want Pi to launch independent agent work with
19
19
  - Live background-work navigator for active runs.
20
20
  - Harness-owned run timing: every run gets a no-progress wake (10 min), while wall-clock soft deadlines and hard ceilings are opt-in so productive agents are not stopped solely for taking a long time. Configure per spawn with `deadline_minutes`, `grace_minutes`, `max_minutes`, `stuck_minutes`, or globally in `config.json` / `PI_SUBAGENT_*_MINUTES`. See [usage notes](docs/usage.md#run-timing-deadline-ceiling-stuck).
21
21
 
22
+ Every single or batch launch automatically joins one shared supervision watcher in the
23
+ foreground Pi process. The last active run's exit or stop tears it down; a later
24
+ launch starts it again. No separate background task or coordinator heartbeat is
25
+ needed. Completion delivery retries use the callback batcher's own timer. Lost-run
26
+ alerts retain supervision until their handoff is handled, so lost work is not silent.
27
+
22
28
  ## Install
23
29
 
24
30
  ```sh
package/catalog-ui.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Input, SelectList, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
- import type { OperationField, OperationList, OperationView } from "./agent-inspection.ts";
1
+ import { Input, SelectList, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
2
+ import type { OperationList, OperationView } from "./agent-inspection.ts";
3
3
  import { EFFORT_LEVELS } from "./catalog-schema.ts";
4
4
  import type { AgentSessionOverrides, AgentSettingKey } from "./agent-session-settings.ts";
5
5
 
@@ -19,9 +19,6 @@ function stateLabel(entry: OperationView): string {
19
19
  return "unresolved";
20
20
  }
21
21
 
22
- function fieldLine(label: string, field: OperationField): string {
23
- return `${label.padEnd(8)} ${field.value ?? "(unset)"} ${field.source === "role-default" ? "inherited" : field.source === "agent-override" ? "override" : "absent"}`;
24
- }
25
22
 
26
23
  function modelLabel(entry: OperationView): string {
27
24
  return entry.actualModel ?? entry.requestedModel ?? entry.fields?.model.value ?? "not resolved";
@@ -49,6 +46,7 @@ export function catalogColumns(entry: OperationView | null, width: number): stri
49
46
  }
50
47
 
51
48
  function wrapLine(text: string, width: number): string[] {
49
+ if (text.includes("\x1b")) return wrapTextWithAnsi(text, width);
52
50
  const rows: string[] = [];
53
51
  let row = "";
54
52
  for (const { segment } of new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text)) {
@@ -62,31 +60,67 @@ function wrapLine(text: string, width: number): string[] {
62
60
  return rows;
63
61
  }
64
62
 
65
- export function catalogDetailLines(entry: OperationView, editable = false): string[] {
63
+ function settingLines(label: string, value: string, origin: string, width: number, marker = " ", theme?: Theme): string[] {
64
+ const title = (text: string) => theme?.fg(marker === "> " ? "accent" : "muted", text) ?? text;
65
+ const source = (text: string) => theme?.fg("dim", text) ?? text;
66
+ if (width < 54) return [title(`${marker}${label}`), ...wrapLine(`${value} ${source(origin)}`, Math.max(1, width - 4)).map((row) => ` ${row}`)];
67
+ const valueWidth = Math.max(1, width - 34);
68
+ return wrapLine(value, valueWidth).map((row, index) =>
69
+ `${index === 0 ? title(marker + label.padEnd(10)) : " ".repeat(12)}${cell(row, valueWidth)} ${index === 0 ? source(origin) : ""}`.trimEnd());
70
+ }
71
+
72
+ export function catalogDetailLines(entry: OperationView, editable = false, width = 80, controls: string[] = [], theme?: Theme): string[] {
73
+ const label = (text: string) => theme?.fg("muted", text) ?? text;
74
+ const heading = (text: string) => label(theme?.bold?.(text) ?? text);
75
+ const contentWidth = Math.max(1, width - 4);
76
+ const columnWidth = width >= 90 ? Math.floor((contentWidth - 4) / 2) : contentWidth;
77
+ const fact = (title: string, value: string) => wrapLine(value, Math.max(1, columnWidth - 13))
78
+ .map((text, index) => `${index === 0 ? label(title.padEnd(13)) : " ".repeat(13)}${text}`);
79
+ const identity = [
80
+ ...fact("ID", entry.id),
81
+ ...fact("Kind", entry.identity.kind ?? "unknown"),
82
+ ...(entry.role ? fact("Base role", `${entry.role.id ?? "(missing)"}${entry.role.found ? "" : " (missing)"}`) : []),
83
+ ];
84
+ const state = [
85
+ ...fact("Status", stateLabel(entry)),
86
+ ...fact("Scope", entry.identity.scope ?? "unknown"),
87
+ ...(entry.instructionMode ? fact("Instructions", entry.instructionMode) : []),
88
+ ];
89
+ const overview = width >= 90
90
+ ? Array.from({ length: Math.max(identity.length, state.length) }, (_, i) =>
91
+ `${cell(identity[i] ?? "", columnWidth)} ${state[i] ?? ""}`.trimEnd())
92
+ : [...identity, ...state];
66
93
  const lines = [
67
- `${entry.identity.name || entry.id} · ${entry.identity.kind ?? "unknown"}`,
68
- entry.id,
94
+ theme?.fg("accent", `${entry.identity.name || entry.id} · ${entry.identity.kind ?? "unknown"}`) ?? `${entry.identity.name || entry.id} · ${entry.identity.kind ?? "unknown"}`,
95
+ ...(entry.identity.description ? wrapLine(entry.identity.description, contentWidth) : []),
69
96
  "",
70
- `Status ${stateLabel(entry)} · ${entry.launchabilityReason}`,
71
- `Source ${entry.identity.scope ?? "unknown"} · ${entry.identity.path ?? "(none)"}`,
72
- ...(entry.identity.description ? [`About ${entry.identity.description}`] : []),
73
- ...(entry.role ? [`Base role ${entry.role.id ?? "(missing)"}${entry.role.found ? "" : " · missing"}`] : []),
74
- ...(entry.instructionMode ? [`Instructions ${entry.instructionMode}`] : []),
97
+ ...overview,
75
98
  "",
76
- "Configuration",
99
+ heading("Configuration"),
100
+ ...(contentWidth >= 54 ? [label(settingLines("SETTING", "VALUE", "ORIGIN", contentWidth)[0])] : []),
101
+ ...controls,
77
102
  ...(entry.fields ? [
78
- ...(!editable ? [fieldLine("Model", entry.fields.model), fieldLine("Effort", entry.fields.effort)] : []),
79
- fieldLine("Tier", entry.fields.tier),
103
+ ...(!editable ? ["model", "effort"].flatMap((key) => {
104
+ const field = entry.fields![key as "model" | "effort"];
105
+ return settingLines(key === "model" ? "Model" : "Effort", field.value ?? "(unset)", field.inherited || field.source === "role-default" ? "inherited" : field.source === "agent-override" ? "override" : "absent", contentWidth, " ", theme);
106
+ }) : []),
107
+ ...settingLines("Tier", entry.fields.tier.value ?? "(unset)", entry.fields.tier.source === "role-default" ? "inherited" : entry.fields.tier.source === "agent-override" ? "override" : "absent", contentWidth, " ", theme),
80
108
  ] : []),
81
- `Actual ${entry.actualModel ?? "not resolved"}${entry.actualEffort ? ` · ${entry.actualEffort}` : ""}`,
82
- ...(entry.validation.length ? ["", "Diagnostics", ...entry.validation.map((item) => `${item.blocking ? "!" : "·"} ${item.message}`)] : []),
83
- ...(entry.shadowed.length ? ["", "Shadowed sources", ...entry.shadowed.map((source) => `${source.scope} ${source.path}`)] : []),
84
- ...(entry.restrictions.length ? ["", "Execution restrictions", ...entry.restrictions.map((item) => `${item.honored ? "honored" : "not honored"} ${item.name}`)] : []),
109
+ `${label("Actual")} ${entry.actualModel ?? "not resolved"}${entry.actualEffort ? ` · ${entry.actualEffort}` : ""}`,
110
+ "",
111
+ heading("Effective prompt"),
112
+ ...(entry.instructions?.trim() ? entry.instructions.split(/\r\n|\r|\n/) : ["(No resolved instructions)"]),
85
113
  "",
86
- "Effective prompt",
87
- "Press p to read the complete resolved instructions.",
114
+ heading("Launch resolution"),
115
+ entry.launchabilityReason,
116
+ "",
117
+ heading("Definition source"),
118
+ entry.identity.path ?? "(none)",
119
+ ...(entry.validation.length ? ["", heading("Diagnostics"), ...entry.validation.map((item) => `${item.blocking ? "!" : "·"} ${item.message}`)] : []),
120
+ ...(entry.shadowed.length ? ["", heading("Shadowed sources"), ...entry.shadowed.map((source) => `${source.scope} ${source.path}`)] : []),
121
+ ...(entry.restrictions.length ? ["", heading("Execution restrictions"), ...entry.restrictions.map((item) => `${item.honored ? "honored" : "not honored"} ${item.name}`)] : []),
88
122
  ];
89
- return lines;
123
+ return lines.flatMap((text) => text ? wrapLine(text, contentWidth).map((row) => ` ${row}`) : [""]);
90
124
  }
91
125
 
92
126
  export function createCatalogComponent(
@@ -103,6 +137,8 @@ export function createCatalogComponent(
103
137
  let query = "";
104
138
  let scroll = 0;
105
139
  let settingRow = 0;
140
+ let settingPositions: number[] = [];
141
+ let revealSetting = false;
106
142
  let picker: SelectList | undefined;
107
143
  let filterPicker: ((filter: string) => void) | undefined;
108
144
  let pickerKey: AgentSettingKey | undefined;
@@ -159,11 +195,11 @@ export function createCatalogComponent(
159
195
  [entry.id, entry.identity.name, entry.identity.description, entry.role?.id]
160
196
  .some((value) => value?.toLowerCase().includes(query.toLowerCase())));
161
197
  const selected = () => filtered().find((entry) => entry.id === selectedId);
162
- const detailRows = (entry: OperationView, width: number) => (mode === "prompt"
198
+ const detailRows = (entry: OperationView, width: number, controls: string[] = []) => (mode === "prompt"
163
199
  ? [`${entry.identity.name || entry.id} · effective instructions`, "", ...(entry.instructions?.split("\n") ?? ["(none)"])]
164
- : catalogDetailLines(entry, !!editor))
200
+ : catalogDetailLines(entry, !!editor, width, controls, theme))
165
201
  .flatMap((text) => text ? wrapLine(text, Math.max(1, width - 2)) : [""]);
166
- let lastDetailWidth = 80;
202
+
167
203
 
168
204
  return {
169
205
  get focused() { return focused; },
@@ -174,21 +210,20 @@ export function createCatalogComponent(
174
210
  const footerRows = (editor && mode !== "prompt" ? 2 : 0) + (message ? 2 : 0);
175
211
  const diagnosticRows = Math.min(catalog.diagnostics.length, 3);
176
212
  const listSize = Math.max(1, height - 5 - footerRows - diagnosticRows - 1);
177
- const controlRows = editor && mode === "detail" ? (safeWidth < 42 ? 5 : 3) : 0;
178
- const detailSize = Math.max(1, height - 5 - footerRows - controlRows);
213
+ const detailSize = Math.max(1, height - 5 - footerRows);
179
214
  const fit = (lines: string[]) => {
180
215
  const result = lines.slice(0, height).map(line);
181
216
  while (result.length < height) result.push("");
182
217
  return result;
183
218
  };
184
- lastDetailWidth = safeWidth;
219
+
185
220
  const line = (text: string) => truncateToWidth(text, safeWidth);
186
221
  const rows = filtered();
187
222
  const current = selected();
188
- const detailLines = current ? detailRows(current, safeWidth) : [];
223
+
189
224
  const selectedIndex = rows.findIndex((entry) => entry.id === selectedId);
190
225
  const start = Math.max(0, Math.min(selectedIndex - Math.floor(listSize / 2), rows.length - listSize));
191
- scroll = Math.max(0, Math.min(scroll, detailLines.length - detailSize));
226
+
192
227
  if (picker) return fit([
193
228
  theme.fg("accent", `Agents / ${pickerKey}`), "",
194
229
  ...(pickerKey === "model" ? search.render(safeWidth) : []),
@@ -203,23 +238,29 @@ export function createCatalogComponent(
203
238
  const ownSession = Object.hasOwn(own ?? {}, key);
204
239
  const roleSession = field?.inherited && Object.hasOwn(editor?.settings()[current.role?.id ?? ""] ?? {}, key);
205
240
  const origin = ownSession && own?.[key] === null ? "inherit / session" : ownSession ? "session" : roleSession ? "inherited / session" : field?.inherited ? "inherited" : "catalog";
206
- const value = `${field?.value ?? "(unset)"} ${origin}`;
207
- const text = `${settingRow === index ? "> " : " "}${label.padEnd(18)} ${value}`;
208
- if (safeWidth < 42) {
209
- const title = `${settingRow === index ? "> " : " "}${label}`;
210
- return [settingRow === index ? highlight(title, safeWidth) : title, ` ${truncateToWidth(value, Math.max(1, safeWidth - 2))}`];
211
- }
212
- return [settingRow === index ? highlight(text, safeWidth) : text];
241
+ return settingLines(label, field?.value ?? "(unset)", origin, Math.max(1, safeWidth - 4), settingRow === index ? "> " : " ", theme);
213
242
  }),
214
- "",
215
243
  ] : [];
244
+ const detailLines = current ? detailRows(current, safeWidth, controls) : [];
245
+ if (editor && mode === "detail") {
246
+ settingPositions = ["Model", "Effort"].map((label) => detailLines.findIndex((text) =>
247
+ new RegExp(`^ [> ] ${label}(?:\\s|$)`).test(text.replace(/\x1b\[[0-9;]*m/g, ""))));
248
+ if (revealSetting && settingPositions[settingRow] >= 0) {
249
+ const position = settingPositions[settingRow];
250
+ if (position < scroll) scroll = position;
251
+ else if (position >= scroll + detailSize) scroll = position - detailSize + 1;
252
+ }
253
+ revealSetting = false;
254
+ }
255
+ scroll = Math.max(0, Math.min(scroll, detailLines.length - detailSize));
216
256
  const lines = mode !== "list" && current ? [
217
257
  theme.fg("accent", mode === "prompt" ? "Agents / prompt" : editor ? `Agents / ${current.identity.name || current.id}` : "Agents / inspect"),
218
258
  theme.fg("dim", mode === "prompt" ? "← details · ↑↓ scroll · Esc back" : `${editor ? "Enter change · " : ""}p prompt · ← list · ↑↓ ${editor ? "select / scroll" : "scroll"} · Esc back`),
219
259
  "",
220
- ...controls,
260
+
221
261
  ...detailLines.slice(scroll, scroll + detailSize).map((text, i) =>
222
- i === 0 && scroll === 0 ? theme.fg("accent", text) : text),
262
+ i === 0 && scroll === 0 ? theme.fg("accent", text)
263
+ : text),
223
264
  "",
224
265
  theme.fg("dim", `Showing ${scroll + 1}-${Math.min(scroll + detailSize, detailLines.length)} of ${detailLines.length} lines`),
225
266
  ] : [
@@ -261,8 +302,12 @@ export function createCatalogComponent(
261
302
  else { close(); return; }
262
303
  } else if (matchesKey(data, "up") || matchesKey(data, "down")) {
263
304
  const delta = matchesKey(data, "down") ? 1 : -1;
264
- if (mode === "detail" && editor && scroll === 0 && (delta < 0 || settingRow === 0)) settingRow = Math.max(0, Math.min(1, settingRow + delta));
265
- else if (mode !== "list" && selected()) scroll = Math.max(0, Math.min(detailRows(selected()!, lastDetailWidth).length - 1, scroll + delta));
305
+ if (mode === "detail" && editor && scroll <= (settingPositions[1] ?? 0)
306
+ && ((delta > 0 && settingRow === 0) || (delta < 0 && settingRow === 1))) {
307
+ settingRow += delta;
308
+ revealSetting = true;
309
+ }
310
+ else if (mode !== "list" && selected()) scroll = Math.max(0, scroll + delta);
266
311
  else if (rows.length) selectedId = rows[Math.max(0, Math.min(rows.length - 1, rows.findIndex((entry) => entry.id === selectedId) + delta))]?.id;
267
312
  } else if (matchesKey(data, "enter") && mode === "list" && selected()) {
268
313
  mode = "detail";
@@ -274,6 +319,7 @@ export function createCatalogComponent(
274
319
  } else if (editor && (data === "e" || data === "E") && mode === "detail" && selected()) {
275
320
  settingRow = 0;
276
321
  scroll = 0;
322
+ revealSetting = true;
277
323
  } else if (editor && mode === "detail" && (matchesKey(data, "enter") || data === " ")) {
278
324
  try { edit(); } catch (cause) { report(cause instanceof Error ? cause.message : String(cause), true); }
279
325
  } else if (mode === "list" && matchesKey(data, "backspace")) {
package/index.ts CHANGED
@@ -879,7 +879,7 @@ function reconcileHealth(): void {
879
879
  if (meta && meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined) enqueueCompletionCallback(pi!, meta.id);
880
880
  }
881
881
  pruneProgressCache();
882
- if (!needsMonitoring(listMetasForParent(process.pid)) && !hasPendingFailureCallbacks()) stopHealthTicker();
882
+ syncHealthTicker();
883
883
  }
884
884
 
885
885
  /** Release progress state for runs that are no longer live (lost, stopped, or finished by any path). */
@@ -948,10 +948,10 @@ function reconcileAbandonedRuns(now: number = Date.now()): number {
948
948
  return adopted;
949
949
  }
950
950
 
951
- function hasPendingFailureCallbacks(): boolean {
952
- return listMetasForParent(process.pid).some((m) => ownedByThisParent(m) && m.callback !== false &&
953
- m.completionCallbackPendingAt !== undefined && m.completionCallbackSentAt === undefined && m.completionCallbackSuppressedAt === undefined &&
954
- !callbackSuppressionReason(m));
951
+ /** Completion batches own their retry timer; only supervision keeps this one alive. */
952
+ function syncHealthTicker(): void {
953
+ if (needsMonitoring(listMetasForParent(process.pid))) ensureHealthTicker();
954
+ else stopHealthTicker();
955
955
  }
956
956
 
957
957
  /** Start the reconciliation loop if it isn't already running. */
@@ -1099,6 +1099,7 @@ function navigatorCloseRun(id: string) {
1099
1099
  healthLogCache.delete(id);
1100
1100
  resetChildEventLogCursor(id);
1101
1101
  resetParseRunCursor(id);
1102
+ syncHealthTicker();
1102
1103
  return outcome;
1103
1104
  }
1104
1105
 
@@ -1451,14 +1452,14 @@ function finalizeRun(pi: ExtensionAPI, ctx: ExtensionContext, id: string, code:
1451
1452
  // Host-facing wrapper around first-party finalizer (finalization.ts).
1452
1453
  // Coherent child-exit evidence may supersede provisional orphaned/lost
1453
1454
  // reconciliation; finalization.ts enforces canExitFinalize + lifecycle authority.
1454
- const result = finalizeRunCore(id, code, {
1455
+ finalizeRunCore(id, code, {
1455
1456
  renderWidget,
1456
1457
  notify: (message, level) => {
1457
1458
  try { ctx.ui.notify(message, level); } catch { /* ignore */ }
1458
1459
  },
1459
1460
  sendMessage: () => enqueueCompletionCallback(pi, id),
1460
1461
  });
1461
- if (result.applied && hasPendingFailureCallbacks()) ensureHealthTicker();
1462
+ syncHealthTicker();
1462
1463
  }
1463
1464
 
1464
1465
  function timingSchemaFields() {
@@ -1938,7 +1939,7 @@ export default function (pi: ExtensionAPI) {
1938
1939
  "The tools param is both the tool allowlist AND what determines which extensions load in the child (e.g. tools='read,bash,web_fetch' loads only the web-tools package). Ask for the tools the task needs and nothing more; clean:true gives a built-ins-only child. Without an agent or role, pick a model with the model param (e.g. 'xai/grok-4.5@high'); providerless model patterns are resolved by Pi, while provider/model is deterministic and loads mapped provider extensions.",
1939
1940
  ...CATALOG_GUIDELINES,
1940
1941
  "Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
1941
- "Every run has harness-owned stall detection: no progress for stuck_minutes (default 10) wakes you once without stopping the run. Elapsed-time limits are opt-in: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
1942
+ "Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. No progress for stuck_minutes (default 10) wakes you once without stopping the run. Elapsed-time limits are opt-in: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
1942
1943
  "Use git_clone_workspace:true when the subagent will mutate Git in a sandbox. The parent prepares a disposable, self-contained clone with a real .git/ directory inside the sandbox root, so linked-worktree metadata outside the sandbox cannot stall the child.",
1943
1944
  ],
1944
1945
  parameters: Type.Object({
@@ -2263,7 +2264,10 @@ export default function (pi: ExtensionAPI) {
2263
2264
  const acceptanceResultTool = subagentResultTool(Type, toolSession);
2264
2265
  pi.registerTool(acceptanceResultTool);
2265
2266
  publishAcceptanceHooks(acceptanceResultTool);
2266
- const acceptanceStopTool = subagentStopTool(Type, { onStopped: renderWidget });
2267
+ const acceptanceStopTool = subagentStopTool(Type, { onStopped: () => {
2268
+ renderWidget();
2269
+ syncHealthTicker();
2270
+ } });
2267
2271
  acceptanceStopToolRef = acceptanceStopTool;
2268
2272
  pi.registerTool(acceptanceStopTool);
2269
2273
  publishAcceptanceHooks();
@@ -2475,10 +2479,8 @@ export default function (pi: ExtensionAPI) {
2475
2479
  // Clear the retired legacy widget so the shared navigator is the only
2476
2480
  // list surface for running/orphaned subagents.
2477
2481
  renderWidget();
2478
- // Resume supervision reconciliation + durable health-callback recovery
2479
- // across /reload while current-parent work still needs the ticker
2480
- // (running/orphaned, or unmarked lost); it stops itself when idle.
2481
- if (needsMonitoring(listMetasForParent(process.pid)) || hasPendingFailureCallbacks()) ensureHealthTicker();
2482
+ // Reattach one watcher after reload; ordinary completion retries belong to the batcher.
2483
+ syncHealthTicker();
2482
2484
  });
2483
2485
 
2484
2486
  pi.on("session_before_switch", () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.21.1",
3
+ "version": "0.22.1",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -328,28 +328,92 @@ function themeFgFromTheme(theme: unknown): (color: string, value: string) => str
328
328
  return (color, value) => maybeTheme?.fg ? maybeTheme.fg(color, value) : value;
329
329
  }
330
330
 
331
- function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, deps: HostDeps): Component & { dispose?(): void } {
331
+ // Structural typing keeps keyboard-only Pi hosts (no mouse API) loading this widget unchanged.
332
+ type WidgetMouseEvent = {
333
+ type: string;
334
+ button: string;
335
+ /** Coordinates local to this component, zero-based. */
336
+ x: number;
337
+ y: number;
338
+ width: number;
339
+ shift?: boolean;
340
+ alt?: boolean;
341
+ ctrl?: boolean;
342
+ };
343
+
344
+ type WidgetMouseResult = { handled: true; render: boolean };
345
+
346
+ type MainListWidget = Component & {
347
+ dispose?(): void;
348
+ handleMouse(event: WidgetMouseEvent): WidgetMouseResult | undefined;
349
+ };
350
+
351
+ function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, deps: HostDeps): MainListWidget {
332
352
  const requestRender = () => tui.requestRender?.();
333
353
  state().mainListRequestRender = requestRender;
354
+ // navigatorId per rendered line, so a pointer row resolves by structure, never by row text.
355
+ let lineOwners: Array<string | undefined> = [];
356
+ let lineWidth = MAIN_LIST_FALLBACK_WIDTH;
357
+ // Pi synthesizes a click only for the component that handled the initial press.
358
+ let pressedRow: { navigatorId: string; y: number } | undefined;
359
+ const rowAt = (event: WidgetMouseEvent): string | undefined => {
360
+ const width = Number.isFinite(event.width) && event.width > 0 ? Math.floor(event.width) : lineWidth;
361
+ if (!Number.isFinite(event.x) || event.x < 0 || event.x >= width) return undefined;
362
+ if (!Number.isInteger(event.y) || event.y < 0 || event.y >= lineOwners.length) return undefined;
363
+ return lineOwners[event.y];
364
+ };
334
365
  return {
335
366
  render(width: number): string[] {
336
367
  const rows = listRows();
337
368
  syncMainListSelection(rows);
338
369
  if (!rows.length) {
339
370
  state().lastMainListLines = undefined;
371
+ lineOwners = [];
372
+ pressedRow = undefined;
340
373
  return [];
341
374
  }
342
- const lines = ["", ...buildMainListLines(rows, renderWidth(width), deps.truncate, themeFgFromTheme(theme), {
375
+ const layout = buildMainListLayout(rows, renderWidth(width), deps.truncate, themeFgFromTheme(theme), {
343
376
  selectedId: state().mainListFocused ? state().mainListSelectedId : undefined,
344
377
  focused: state().mainListFocused === true,
345
- })];
378
+ });
379
+ lineWidth = renderWidth(width);
380
+ // The leading gap line belongs to the widget too, so its slot stays ownerless.
381
+ lineOwners = [undefined, ...layout.owners];
382
+ const lines = ["", ...layout.lines];
346
383
  state().lastMainListLines = lines;
347
384
  return lines;
348
385
  },
349
- invalidate() { state().lastMainListLines = undefined; },
386
+ handleMouse(event: WidgetMouseEvent): WidgetMouseResult | undefined {
387
+ // Only an unmodified left press is ours; every other gesture reaches the host untouched.
388
+ if (event.button !== "left" || event.shift === true || event.alt === true || event.ctrl === true) {
389
+ pressedRow = undefined;
390
+ return undefined;
391
+ }
392
+ if (event.type === "press") {
393
+ pressedRow = undefined;
394
+ const navigatorId = rowAt(event);
395
+ if (!navigatorId || !listRows().some((row) => row.navigatorId === navigatorId)) return undefined;
396
+ pressedRow = { navigatorId, y: event.y };
397
+ return { handled: true, render: false };
398
+ }
399
+ if (event.type !== "click") return undefined;
400
+ const pressed = pressedRow;
401
+ pressedRow = undefined;
402
+ // A click after another component's press, or after the layout moved, is not the row we claimed.
403
+ if (!pressed || pressed.y !== event.y || rowAt(event) !== pressed.navigatorId) return undefined;
404
+ if (!openNavigatorRow(pressed.navigatorId)) return undefined;
405
+ return { handled: true, render: true };
406
+ },
407
+ invalidate() {
408
+ state().lastMainListLines = undefined;
409
+ lineOwners = [];
410
+ pressedRow = undefined;
411
+ },
350
412
  dispose() {
351
413
  const s = state();
352
414
  if (s.mainListRequestRender === requestRender) s.mainListRequestRender = undefined;
415
+ lineOwners = [];
416
+ pressedRow = undefined;
353
417
  },
354
418
  };
355
419
  }
@@ -454,7 +518,26 @@ function buildMainListLines(
454
518
  fg: (color: string, value: string) => string,
455
519
  options: { selectedId?: string; focused?: boolean } = {},
456
520
  ): string[] {
521
+ return buildMainListLayout(rows, width, truncate, fg, options).lines;
522
+ }
523
+
524
+ /**
525
+ * The list's lines plus the navigatorId each line shows, so pointer input maps a rendered row to its
526
+ * stable row identity. Headers, separators and the shortcut line keep an undefined owner.
527
+ */
528
+ function buildMainListLayout(
529
+ rows: InternalRow[],
530
+ width: number,
531
+ truncate: (s: string, width: number) => string,
532
+ fg: (color: string, value: string) => string,
533
+ options: { selectedId?: string; focused?: boolean } = {},
534
+ ): { lines: string[]; owners: Array<string | undefined> } {
457
535
  const lines: string[] = [];
536
+ const owners: Array<string | undefined> = [];
537
+ const push = (line: string, owner?: string) => {
538
+ lines.push(line);
539
+ owners.push(owner);
540
+ };
458
541
  const grouped = new Map<string, InternalRow[]>();
459
542
  for (const row of rows) {
460
543
  const existing = grouped.get(row.providerLabel) ?? [];
@@ -466,16 +549,16 @@ function buildMainListLines(
466
549
  for (let i = 0; i < orderedLabels.length; i += 1) {
467
550
  const label = orderedLabels[i]!;
468
551
  const group = grouped.get(label)!;
469
- if (i > 0) lines.push("");
470
- lines.push(providerGroupLabel(label, fg));
552
+ if (i > 0) push("");
553
+ push(providerGroupLabel(label, fg));
471
554
  for (const row of group) {
472
555
  const selected = options.focused && row.navigatorId === options.selectedId;
473
- lines.push(formatMainListRow(row, selected === true, fg, width));
556
+ push(formatMainListRow(row, selected === true, fg, width), row.navigatorId);
474
557
  }
475
558
  }
476
- lines.push("");
477
- lines.push(shortcutsLine(options.focused === true, fg));
478
- return lines.map((line) => safeTruncate(line, width, truncate));
559
+ push("");
560
+ push(shortcutsLine(options.focused === true, fg));
561
+ return { lines: lines.map((line) => safeTruncate(line, width, truncate)), owners };
479
562
  }
480
563
 
481
564
  function shortcutsLine(focused: boolean, fg: (color: string, value: string) => string): string {
@@ -766,6 +849,20 @@ function handleMainListCloseKey(): void {
766
849
  refreshMainListWidget();
767
850
  }
768
851
 
852
+ /**
853
+ * Open the shared detail overlay on the row a pointer chose. Setting the selection first keeps the
854
+ * keyboard path identical: Enter, x and the overlay's own keys then act on the clicked row.
855
+ */
856
+ function openNavigatorRow(navigatorId: string): boolean {
857
+ const rows = listRows();
858
+ if (!rows.some((row) => row.navigatorId === navigatorId)) return false;
859
+ clearMainListCloseArm();
860
+ state().mainListSelectedId = navigatorId;
861
+ refreshMainListWidget();
862
+ openNavigator();
863
+ return true;
864
+ }
865
+
769
866
  function openNavigator(): void {
770
867
  const s = state();
771
868
  const ctx = s.uiCtx;