pi-subagent-manager 1.10.0 → 1.12.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 (95) hide show
  1. package/README.md +9 -9
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.js +790 -0
  4. package/dist/orch/checklist-integration.js +176 -0
  5. package/dist/orch/context-entries.js +6 -0
  6. package/dist/orch/cost-ledger.js +38 -0
  7. package/dist/orch/diagnostics.js +86 -0
  8. package/dist/orch/extensions.js +66 -0
  9. package/dist/orch/housekeeping-usage.js +22 -0
  10. package/dist/orch/housekeeping.js +248 -0
  11. package/dist/orch/inherited-tools.js +57 -0
  12. package/dist/orch/mailbox.js +195 -0
  13. package/dist/orch/manager.js +970 -0
  14. package/dist/orch/paths.js +69 -0
  15. package/dist/orch/prompt.js +30 -0
  16. package/dist/orch/registry.js +115 -0
  17. package/dist/orch/runtime.js +835 -0
  18. package/dist/orch/tools.js +112 -0
  19. package/dist/orch/transcript.js +165 -0
  20. package/dist/prefs/agent-import.js +188 -0
  21. package/dist/prefs/config.js +878 -0
  22. package/dist/prefs/import-discovery.js +547 -0
  23. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +0 -1
  24. package/dist/prefs/models.js +56 -0
  25. package/dist/prefs/settings.js +491 -0
  26. package/dist/types.js +1 -0
  27. package/dist/ui/agent-loader.js +63 -0
  28. package/dist/ui/agent-navigation-editor.js +168 -0
  29. package/dist/ui/cost-footer.js +209 -0
  30. package/dist/ui/dialog.js +505 -0
  31. package/dist/ui/import-picker.js +191 -0
  32. package/dist/ui/live-agent-view.js +527 -0
  33. package/dist/ui/model-picker.js +529 -0
  34. package/dist/ui/settings-ui.js +671 -0
  35. package/dist/ui/status-ui.js +470 -0
  36. package/dist/ui/thread-tree.js +142 -0
  37. package/dist/ui/tool-picker.js +331 -0
  38. package/dist/ui/transcript-tool.js +91 -0
  39. package/dist/ui/ui.js +1019 -0
  40. package/package.json +17 -5
  41. package/docs/assets/subagent-manager-demo.gif +0 -0
  42. package/docs/async-lifecycle.md +0 -153
  43. package/docs/custom-agents.md +0 -154
  44. package/docs/default-agents.md +0 -95
  45. package/docs/demo.md +0 -63
  46. package/docs/development.md +0 -74
  47. package/docs/importing-agents.md +0 -41
  48. package/docs/pi-footer.md +0 -128
  49. package/docs/research-claude.md +0 -258
  50. package/docs/research-codex.md +0 -143
  51. package/docs/research-default-agent-models.md +0 -121
  52. package/docs/research-model-audit-2026-10.md +0 -154
  53. package/docs/research-model-roles-coding.md +0 -99
  54. package/docs/research-model-roles-writing.md +0 -78
  55. package/docs/research-researcher-workflow.md +0 -97
  56. package/docs/settings.md +0 -293
  57. package/docs/subagent-extension-limitations.md +0 -98
  58. package/docs/threads.md +0 -73
  59. package/docs/tools-and-ui.md +0 -129
  60. package/src/index.ts +0 -920
  61. package/src/orch/checklist-integration.ts +0 -230
  62. package/src/orch/context-entries.ts +0 -15
  63. package/src/orch/cost-ledger.ts +0 -56
  64. package/src/orch/diagnostics.ts +0 -95
  65. package/src/orch/extensions.ts +0 -83
  66. package/src/orch/housekeeping-usage.ts +0 -47
  67. package/src/orch/housekeeping.ts +0 -348
  68. package/src/orch/inherited-tools.ts +0 -84
  69. package/src/orch/mailbox.ts +0 -261
  70. package/src/orch/manager.ts +0 -1084
  71. package/src/orch/paths.ts +0 -73
  72. package/src/orch/prompt.ts +0 -39
  73. package/src/orch/registry.ts +0 -168
  74. package/src/orch/runtime.ts +0 -1041
  75. package/src/orch/tools.ts +0 -190
  76. package/src/orch/transcript.ts +0 -186
  77. package/src/prefs/agent-import.ts +0 -245
  78. package/src/prefs/config.ts +0 -1017
  79. package/src/prefs/import-discovery.ts +0 -643
  80. package/src/prefs/models.ts +0 -74
  81. package/src/prefs/settings.ts +0 -614
  82. package/src/types.ts +0 -271
  83. package/src/ui/agent-loader.ts +0 -98
  84. package/src/ui/agent-navigation-editor.ts +0 -233
  85. package/src/ui/cost-footer.ts +0 -230
  86. package/src/ui/dialog.ts +0 -678
  87. package/src/ui/import-picker.ts +0 -231
  88. package/src/ui/live-agent-view.ts +0 -600
  89. package/src/ui/model-picker.ts +0 -701
  90. package/src/ui/settings-ui.ts +0 -830
  91. package/src/ui/status-ui.ts +0 -628
  92. package/src/ui/thread-tree.ts +0 -173
  93. package/src/ui/tool-picker.ts +0 -398
  94. package/src/ui/transcript-tool.ts +0 -142
  95. package/src/ui/ui.ts +0 -1407
package/src/ui/dialog.ts DELETED
@@ -1,678 +0,0 @@
1
- import type {
2
- ExtensionContext,
3
- ExtensionUIContext,
4
- KeybindingsManager,
5
- Theme,
6
- } from "@earendil-works/pi-coding-agent";
7
- import {
8
- CURSOR_MARKER,
9
- Editor,
10
- getKeybindings,
11
- Input,
12
- Key,
13
- matchesKey,
14
- stripTerminalSequences,
15
- truncateToWidth,
16
- visibleWidth,
17
- wrapTextWithAnsi,
18
- type Component,
19
- type TUI,
20
- type TuiMouseEvent,
21
- type TuiMouseEventResult,
22
- } from "@earendil-works/pi-tui";
23
-
24
- export interface DialogHost {
25
- requestRender(force?: boolean): void;
26
- terminal?: { rows: number };
27
- }
28
- export interface DialogEditorHost extends DialogHost {
29
- terminal: { rows: number };
30
- }
31
- export interface DialogRow {
32
- id: string;
33
- label: string;
34
- /** Trusted formatter receives sanitized text; generated ANSI styling is kept when clipping. */
35
- renderLabel?: (label: string, theme: Theme) => string;
36
- /** Trusted formatter for a fixed three-cell middle column, styled at render time. */
37
- renderIndicators?: (theme: Theme) => string;
38
- value?: string;
39
- /** Optional second line beneath the value, clipped to the same column. */
40
- valueDetail?: string;
41
- valueColor?: Parameters<Theme["fg"]>[0];
42
- help?: string;
43
- }
44
- export const DIALOG_OPTIONS = {
45
- overlay: true,
46
- overlayOptions: {
47
- anchor: "center",
48
- width: "90%",
49
- maxHeight: "90%",
50
- margin: 1,
51
- },
52
- } as const;
53
-
54
- export function dialogText(text: string): string {
55
- return stripTerminalSequences(text).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
56
- }
57
-
58
- /** Match Pi's overlay height calculation; maxHeight alone would clip the bottom border. */
59
- export function dialogHeight(host: DialogHost): number {
60
- const rows = host.terminal?.rows ?? 24;
61
- return Math.max(1, Math.min(rows - 2, Math.floor(rows * 0.9)));
62
- }
63
-
64
- export function frameDialog(
65
- theme: Theme,
66
- width: number,
67
- height: number,
68
- title: string,
69
- body: string[],
70
- footer: string,
71
- ): string[] {
72
- if (width <= 0 || height <= 0) return [];
73
- const fit = (text: string, columns: number) => {
74
- const clipped = truncateToWidth(text, Math.max(0, columns), "", true);
75
- return clipped + " ".repeat(Math.max(0, columns - visibleWidth(clipped)));
76
- };
77
- if (width < 4 || height < 4) return [fit(theme.fg("muted", dialogText(title)), width)];
78
- const inner = width - 2;
79
- const line = (text: string) =>
80
- theme.fg("border", "│") + fit(text, inner) + theme.fg("border", "│");
81
- const heading = truncateToWidth(` ${dialogText(title)} `, inner, "");
82
- const top = theme.fg(
83
- "border",
84
- "╭" + heading + "─".repeat(Math.max(0, inner - visibleWidth(heading))) + "╮",
85
- );
86
- // Pad to the full frame so centered overlays keep the same bounds between views.
87
- const budget = height - 4;
88
- const padded = body.slice(0, budget);
89
- while (padded.length < budget) padded.push("");
90
- const content = padded.map(line);
91
- return [
92
- top,
93
- ...content,
94
- theme.fg("border", "├" + "─".repeat(inner) + "┤"),
95
- line(theme.fg("dim", dialogText(footer))),
96
- theme.fg("border", "╰" + "─".repeat(inner) + "╯"),
97
- ];
98
- }
99
-
100
- /** A multiline editor inside the same bounded shell as the surrounding form. */
101
- export class DialogEditor {
102
- private editor: Editor;
103
- private initialText: string;
104
- constructor(
105
- private host: DialogEditorHost,
106
- private theme: Theme,
107
- readonly title: string,
108
- readonly prefill: string,
109
- private done: (value: string | undefined) => void,
110
- ) {
111
- this.editor = new Editor(
112
- host as ConstructorParameters<typeof Editor>[0],
113
- {
114
- borderColor: (text) => theme.fg("border", text),
115
- selectList: {
116
- selectedPrefix: (text) => theme.fg("accent", text),
117
- selectedText: (text) => theme.fg("accent", text),
118
- description: (text) => theme.fg("muted", text),
119
- scrollInfo: (text) => theme.fg("dim", text),
120
- noMatch: (text) => theme.fg("warning", text),
121
- },
122
- },
123
- { paddingX: 0 },
124
- );
125
- this.editor.setText(
126
- stripTerminalSequences(prefill)
127
- .replace(/\r\n?/g, "\n")
128
- .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, ""),
129
- );
130
- this.initialText = this.editor.getText();
131
- this.editor.disableSubmit = true;
132
- }
133
- getEditor(): Editor {
134
- return this.editor;
135
- }
136
- get focused(): boolean {
137
- return this.editor.focused;
138
- }
139
- set focused(value: boolean) {
140
- this.editor.focused = value;
141
- }
142
- handleInput(data: string): void {
143
- if (matchesKey(data, Key.escape)) return this.done(undefined);
144
- if (matchesKey(data, Key.ctrl("s"))) {
145
- const value = this.editor.getText();
146
- return this.done(value === this.initialText ? this.prefill : value);
147
- }
148
- this.editor.handleInput(data);
149
- this.host.requestRender();
150
- }
151
- invalidate(): void {
152
- this.editor.invalidate();
153
- }
154
- render(width: number): string[] {
155
- const height = dialogHeight(this.host);
156
- const rows = this.editor.render(Math.max(1, width - 4)).slice(1, -1);
157
- const budget = Math.max(0, height - 4);
158
- const cursor = rows.findIndex((line) => line.includes(CURSOR_MARKER));
159
- const start = cursor >= budget ? cursor - budget + 1 : 0;
160
- return frameDialog(
161
- this.theme,
162
- width,
163
- height,
164
- this.title,
165
- rows.slice(start, start + budget).map((line) => ` ${line}`),
166
- "Enter newline · Ctrl+S apply · Esc cancel",
167
- );
168
- }
169
- }
170
-
171
- export function dialogEditor(
172
- ctx: ExtensionContext,
173
- title: string,
174
- prefill: string,
175
- ): Promise<string | undefined> {
176
- return ctx.ui.custom(
177
- (host, theme, _keys, done) => new DialogEditor(host, theme, title, prefill, done),
178
- DIALOG_OPTIONS,
179
- );
180
- }
181
-
182
- /** Bounded menu with an optional indicator column, shared by settings and agent definitions. */
183
- export class DialogMenu {
184
- private selected = 0;
185
- private viewport = 1;
186
- constructor(
187
- private host: DialogHost,
188
- private theme: Theme,
189
- readonly title: string,
190
- readonly rows: DialogRow[],
191
- private done: (id: string | undefined) => void,
192
- selectedId?: string,
193
- readonly footer = "↑↓ navigate · Enter select · Esc close",
194
- private saveId?: string,
195
- private renderLegend?: (theme: Theme) => string,
196
- private spaceSelect = false,
197
- ) {
198
- const index = rows.findIndex((row) => row.id === selectedId);
199
- if (index >= 0) this.selected = index;
200
- }
201
- getSelectedId(): string | undefined {
202
- return this.rows[this.selected]?.id;
203
- }
204
- handleInput(data: string): void {
205
- const keys = getKeybindings();
206
- if (keys.matches(data, "tui.select.cancel")) return this.done(undefined);
207
- if (
208
- keys.matches(data, "tui.select.confirm") ||
209
- (this.spaceSelect && matchesKey(data, Key.space))
210
- )
211
- return this.done(this.getSelectedId());
212
- if (this.saveId && matchesKey(data, Key.ctrl("s"))) return this.done(this.saveId);
213
- let offset = 0;
214
- if (keys.matches(data, "tui.select.up")) offset = -1;
215
- else if (keys.matches(data, "tui.select.down") || matchesKey(data, Key.tab)) offset = 1;
216
- else if (matchesKey(data, Key.pageUp)) offset = -this.viewport;
217
- else if (matchesKey(data, Key.pageDown)) offset = this.viewport;
218
- else if (matchesKey(data, Key.home)) this.selected = 0;
219
- else if (matchesKey(data, Key.end)) this.selected = Math.max(0, this.rows.length - 1);
220
- this.selected = Math.max(0, Math.min(this.rows.length - 1, this.selected + offset));
221
- this.host.requestRender();
222
- }
223
- invalidate(): void {}
224
- render(width: number): string[] {
225
- const height = dialogHeight(this.host);
226
- const inner = Math.max(0, width - 4);
227
- const legend = this.renderLegend
228
- ? wrapTextWithAnsi(this.renderLegend(this.theme), Math.max(1, inner - 1))
229
- .slice(0, Math.max(0, height - 8))
230
- .map((line) => ` ${line}`)
231
- : [];
232
- const help = (this.rows[this.selected]?.help ?? "")
233
- .split(/\r\n?|\n/)
234
- .flatMap((line) => wrapTextWithAnsi(dialogText(line), Math.max(1, inner - 1)))
235
- .slice(0, Math.max(1, height - 7 - legend.length));
236
- const rowHeight = this.rows.some((row) => row.valueDetail !== undefined) ? 2 : 1;
237
- this.viewport = Math.max(1, Math.floor((height - 6 - help.length - legend.length) / rowHeight));
238
- const start = Math.max(
239
- 0,
240
- Math.min(this.selected - this.viewport + 1, this.rows.length - this.viewport),
241
- );
242
- const hasIndicators = this.rows.some((row) => row.renderIndicators);
243
- const indicatorWidth = 3;
244
- const labelWidth = Math.min(
245
- 28,
246
- Math.max(8, Math.floor(inner * 0.35)),
247
- // Reserve prefix, separators, indicators and at least one value cell at narrow widths.
248
- hasIndicators ? Math.max(0, inner - 2 - 6 - indicatorWidth - 1) : Infinity,
249
- );
250
- const body = [
251
- this.theme.fg(
252
- "dim",
253
- ` ${this.rows.length ? this.selected + 1 : 0}/${this.rows.length} · Field / ${hasIndicators ? "Saved / " : ""}Value`,
254
- ),
255
- ...this.rows.slice(start, start + this.viewport).flatMap((row, i) => {
256
- const selected = start + i === this.selected;
257
- const color = (text: string) => (selected ? this.theme.fg("accent", text) : text);
258
- const plainLabel = dialogText(row.label);
259
- const label = truncateToWidth(
260
- row.renderLabel ? row.renderLabel(plainLabel, this.theme) : plainLabel,
261
- labelWidth,
262
- "",
263
- true,
264
- );
265
- const padding = " ".repeat(Math.max(0, labelWidth - visibleWidth(label)));
266
- const indicators = truncateToWidth(
267
- row.renderIndicators?.(this.theme) ?? "",
268
- indicatorWidth,
269
- "",
270
- true,
271
- );
272
- const indicatorPadding = " ".repeat(Math.max(0, indicatorWidth - visibleWidth(indicators)));
273
- const value = dialogText(row.value ?? "");
274
- const primary =
275
- color(`${selected ? "›" : " "} `) +
276
- (row.renderLabel ? label : color(label)) +
277
- color(`${padding} │ `) +
278
- (hasIndicators ? indicators + color(`${indicatorPadding} │ `) : "") +
279
- (row.valueColor ? this.theme.fg(row.valueColor, value) : color(value));
280
- if (rowHeight === 1) return [primary];
281
- const valueStart = 2 + labelWidth + 3 + (hasIndicators ? indicatorWidth + 3 : 0);
282
- const detail = truncateToWidth(
283
- dialogText(row.valueDetail ?? ""),
284
- Math.max(0, inner - valueStart),
285
- );
286
- return [primary, " ".repeat(valueStart) + this.theme.fg("muted", detail)];
287
- }),
288
- "",
289
- ...help.map((line) => this.theme.fg("muted", ` ${line}`)),
290
- ];
291
- if (legend.length) {
292
- const budget = Math.max(0, height - 4 - legend.length);
293
- body.length = Math.min(body.length, budget);
294
- while (body.length < budget) body.push("");
295
- body.push(...legend);
296
- }
297
- return frameDialog(this.theme, width, height, this.title, body, this.footer);
298
- }
299
- }
300
-
301
- export function canOpenDialog(ctx: ExtensionContext): boolean {
302
- if (!ctx.hasUI) return false;
303
- if (ctx.mode && ctx.mode !== "tui") {
304
- ctx.ui.notify("Agents dialogs require interactive TUI mode.", "warning");
305
- return false;
306
- }
307
- return true;
308
- }
309
-
310
- export async function dialogMenu(
311
- ctx: ExtensionContext,
312
- title: string,
313
- rows: DialogRow[],
314
- options: {
315
- selectedId?: string;
316
- footer?: string;
317
- saveId?: string;
318
- renderLegend?: (theme: Theme) => string;
319
- spaceSelect?: boolean;
320
- } = {},
321
- ): Promise<string | undefined> {
322
- return ctx.ui.custom(
323
- (host, theme, _keys, done) =>
324
- new DialogMenu(
325
- host,
326
- theme,
327
- title,
328
- rows,
329
- done,
330
- options.selectedId,
331
- options.footer,
332
- options.saveId,
333
- options.renderLegend,
334
- options.spaceSelect,
335
- ),
336
- DIALOG_OPTIONS,
337
- );
338
- }
339
-
340
- export async function dialogInput(
341
- ctx: ExtensionContext,
342
- title: string,
343
- initial: string,
344
- help: string,
345
- ): Promise<string | undefined> {
346
- return ctx.ui.custom<string | undefined>((host, theme, _keys, done) => {
347
- const input = new Input();
348
- input.setValue(dialogText(initial));
349
- input.onSubmit = done;
350
- input.onEscape = () => done(undefined);
351
- return {
352
- get focused() {
353
- return input.focused;
354
- },
355
- set focused(value: boolean) {
356
- input.focused = value;
357
- },
358
- handleInput: (data: string) => {
359
- input.handleInput(data);
360
- host.requestRender();
361
- },
362
- invalidate: () => input.invalidate(),
363
- render: (width: number) =>
364
- frameDialog(
365
- theme,
366
- width,
367
- dialogHeight(host),
368
- title,
369
- [
370
- "",
371
- ...input.render(Math.max(1, width - 4)).map((line) => ` ${line}`),
372
- "",
373
- ...help
374
- .split(/\r\n?|\n/)
375
- .flatMap((line) => wrapTextWithAnsi(dialogText(line), Math.max(1, width - 5)))
376
- .map((line) => theme.fg("muted", ` ${line}`)),
377
- ],
378
- "Enter apply · Esc cancel",
379
- ),
380
- };
381
- }, DIALOG_OPTIONS);
382
- }
383
-
384
- type DialogView = Component & {
385
- dispose?(): void;
386
- focused?: boolean;
387
- };
388
-
389
- type DialogFactory<T> = (
390
- host: TUI,
391
- theme: Theme,
392
- keys: KeybindingsManager,
393
- done: (result: T) => void,
394
- ) => DialogView | Promise<DialogView>;
395
-
396
- interface PendingView {
397
- generation: number;
398
- settled: boolean;
399
- resolve: (value: unknown) => void;
400
- }
401
-
402
- const dialogScopes = new WeakSet<ExtensionContext>();
403
-
404
- function isPromise<T>(value: T | Promise<T>): value is Promise<T> {
405
- return (
406
- typeof value === "object" && value !== null && typeof (value as Promise<T>).then === "function"
407
- );
408
- }
409
-
410
- function safeDispose(component: DialogView | undefined): void {
411
- if (!component?.dispose) return;
412
- try {
413
- component.dispose();
414
- } catch {
415
- // A view that fails to dispose must not reject the session promise.
416
- }
417
- }
418
-
419
- /** One overlay for a multi-step dialog. Child views swap without closing it. */
420
- export class DialogSession {
421
- private child: DialogView | undefined;
422
- private focusedState = false;
423
- private inputLocked = true;
424
- private closed = false;
425
- private disposed = false;
426
- private generation = 0;
427
- private pending: PendingView | undefined;
428
- private outerDone: ((result?: void) => void) | undefined;
429
-
430
- constructor(
431
- private host: TUI,
432
- private theme: Theme,
433
- private keys: KeybindingsManager,
434
- done: (result?: void) => void,
435
- ) {
436
- this.outerDone = done;
437
- }
438
-
439
- /** Current or last held child. Tests drive the active editor through this. */
440
- getComponent(): DialogView | undefined {
441
- return this.child;
442
- }
443
-
444
- restoreFocus(): void {
445
- if (this.closed) return;
446
- // Non-overlay custom views restore Pi's normal editor when they finish.
447
- this.host.setFocus(this);
448
- this.host.requestRender();
449
- }
450
-
451
- get focused(): boolean {
452
- return this.focusedState;
453
- }
454
-
455
- set focused(value: boolean) {
456
- this.focusedState = value;
457
- this.forwardFocus();
458
- }
459
-
460
- /**
461
- * Mount an overlay factory into this session. The returned promise settles
462
- * from the per-view done callback and does not complete the outer overlay.
463
- */
464
- mount<T>(factory: DialogFactory<T>): Promise<T> {
465
- if (this.closed) return Promise.resolve(undefined as T);
466
- const generation = ++this.generation;
467
- this.inputLocked = true;
468
- this.resolvePending();
469
-
470
- return new Promise<T>((resolve, reject) => {
471
- let settled = false;
472
- const resolveOnce = (value: T) => {
473
- if (settled) return;
474
- settled = true;
475
- if (this.pending?.generation === generation) this.pending.settled = true;
476
- resolve(value);
477
- };
478
- const rejectOnce = (error: unknown) => {
479
- if (settled) return;
480
- settled = true;
481
- this.inputLocked = true;
482
- if (this.pending?.generation === generation) this.pending.settled = true;
483
- reject(error);
484
- };
485
- this.pending = {
486
- generation,
487
- settled: false,
488
- resolve: (value) => resolveOnce(value as T),
489
- };
490
-
491
- const finish = (value: T) => {
492
- if (this.closed || generation !== this.generation) return;
493
- this.inputLocked = true;
494
- resolveOnce(value);
495
- };
496
-
497
- const adopt = (component: DialogView) => {
498
- try {
499
- this.install(generation, component);
500
- } catch (error) {
501
- rejectOnce(error);
502
- }
503
- };
504
-
505
- try {
506
- const produced = factory(this.host, this.theme, this.keys, finish);
507
- if (isPromise(produced)) {
508
- void produced.then(
509
- (component) => adopt(component),
510
- (error: unknown) => {
511
- if (settled || this.closed || generation !== this.generation) return;
512
- rejectOnce(error);
513
- },
514
- );
515
- } else {
516
- adopt(produced);
517
- }
518
- } catch (error) {
519
- // done() may already have resolved; don't reject a settled view or leave a throw unhandled.
520
- rejectOnce(error);
521
- }
522
- });
523
- }
524
-
525
- handleInput(data: string): void {
526
- if (this.closed || this.inputLocked) return;
527
- this.child?.handleInput?.(data);
528
- }
529
-
530
- /** Fullscreen mouse events reach the overlay, so forward them to the active child view. */
531
- handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
532
- if (this.closed || this.inputLocked) return undefined;
533
- return this.child?.handleMouse?.(event);
534
- }
535
-
536
- invalidate(): void {
537
- this.child?.invalidate();
538
- }
539
-
540
- render(width: number): string[] {
541
- return this.child?.render(width) ?? [];
542
- }
543
-
544
- dispose(): void {
545
- if (this.disposed) return;
546
- this.disposed = true;
547
- this.closed = true;
548
- this.inputLocked = true;
549
- this.resolvePending();
550
- const child = this.child;
551
- this.child = undefined;
552
- safeDispose(child);
553
- }
554
-
555
- /** Complete the outer overlay once. Safe to call after the host already closed. */
556
- close(): void {
557
- if (this.closed) return;
558
- this.closed = true;
559
- this.inputLocked = true;
560
- this.resolvePending();
561
- const done = this.outerDone;
562
- this.outerDone = undefined;
563
- try {
564
- done?.();
565
- } finally {
566
- this.dispose();
567
- }
568
- }
569
-
570
- private install(generation: number, component: DialogView): void {
571
- if (this.closed || generation !== this.generation) {
572
- safeDispose(component);
573
- return;
574
- }
575
- this.replaceChild(component);
576
- this.inputLocked = this.pending?.generation === generation ? this.pending.settled : true;
577
- this.host.requestRender();
578
- }
579
-
580
- private replaceChild(next: DialogView): void {
581
- const previous = this.child;
582
- this.child = next;
583
- this.forwardFocus();
584
- if (!previous || previous === next) return;
585
- if ("focused" in previous) previous.focused = false;
586
- safeDispose(previous);
587
- }
588
-
589
- private forwardFocus(): void {
590
- const child = this.child;
591
- if (!child || !("focused" in child)) return;
592
- // Read the setter's latest value; the first view can mount before showOverlay focuses us.
593
- child.focused = this.focused;
594
- }
595
-
596
- private resolvePending(): void {
597
- const pending = this.pending;
598
- if (!pending || pending.settled) return;
599
- pending.settled = true;
600
- pending.resolve(undefined);
601
- }
602
- }
603
-
604
- export function scopeDialogContext<T extends ExtensionContext>(ctx: T, session: DialogSession): T {
605
- const source = ctx.ui;
606
- const originalCustom = source.custom.bind(source);
607
- const ui = Object.create(source) as ExtensionUIContext;
608
- ui.custom = ((factory, options) => {
609
- if (options?.overlay) return session.mount(factory);
610
- return originalCustom(factory, options).finally(() => session.restoreFocus());
611
- }) as ExtensionUIContext["custom"];
612
- // Pi exposes ctx.ui as a getter; assignment cannot shadow an inherited accessor.
613
- // Define an own property while keeping the remaining context getters live.
614
- return Object.create(ctx, {
615
- ui: { value: ui, writable: true, enumerable: true, configurable: true },
616
- }) as T;
617
- }
618
-
619
- /**
620
- * Run a dialog workflow inside one ctx.ui.custom overlay.
621
- * Nested calls on the scoped context reuse that overlay instead of opening another.
622
- */
623
- export async function withDialogSession<T extends ExtensionContext>(
624
- ctx: T,
625
- run: (ctx: T) => Promise<void>,
626
- ): Promise<void> {
627
- if (dialogScopes.has(ctx)) {
628
- await run(ctx);
629
- return;
630
- }
631
-
632
- let failure: unknown;
633
- let failed = false;
634
- let session: DialogSession | undefined;
635
- try {
636
- await ctx.ui.custom<void>((host, theme, keys, done) => {
637
- session = new DialogSession(host, theme, keys, done);
638
- const scoped = scopeDialogContext(ctx, session);
639
- dialogScopes.add(scoped);
640
- // Pi mounts the returned component in a Promise continuation. Defer the
641
- // workflow so even an immediate return/throw closes after that mount.
642
- const task = Promise.resolve().then(() => run(scoped));
643
- void task.then(
644
- () => {
645
- try {
646
- session?.close();
647
- } catch (error) {
648
- if (!failed) {
649
- failed = true;
650
- failure = error;
651
- }
652
- }
653
- },
654
- (error: unknown) => {
655
- failed = true;
656
- failure = error;
657
- try {
658
- session?.close();
659
- } catch (closeError) {
660
- failure ??= closeError;
661
- }
662
- },
663
- );
664
- return session;
665
- }, DIALOG_OPTIONS);
666
- } catch (error) {
667
- try {
668
- session?.close();
669
- } catch {
670
- // The original custom rejection is the one that must propagate.
671
- }
672
- if (!failed) {
673
- failed = true;
674
- failure = error;
675
- }
676
- }
677
- if (failed) throw failure;
678
- }