@pellux/goodvibes-tui 0.18.13 → 0.18.17

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 (65) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +1 -1
  3. package/docs/foundation-artifacts/operator-contract.json +1 -1
  4. package/package.json +3 -2
  5. package/src/daemon/cli.ts +82 -6
  6. package/src/input/command-registry.ts +2 -0
  7. package/src/input/commands/control-room-runtime.ts +1 -1
  8. package/src/input/commands/health-runtime.ts +1 -1
  9. package/src/input/commands/local-setup-review.ts +1 -1
  10. package/src/input/commands/platform-access-runtime.ts +1 -1
  11. package/src/input/commands/qrcode-runtime.ts +20 -0
  12. package/src/input/commands/subscription-runtime.ts +1 -1
  13. package/src/input/commands.ts +2 -0
  14. package/src/input/handler-feed.ts +6 -0
  15. package/src/input/handler-modal-routes.ts +19 -2
  16. package/src/input/handler-modal-token-routes.ts +3 -0
  17. package/src/input/handler-picker-routes.ts +4 -2
  18. package/src/input/model-picker.ts +11 -0
  19. package/src/input/settings-modal.ts +31 -3
  20. package/src/panels/agent-logs-panel.ts +23 -24
  21. package/src/panels/builtin/session.ts +66 -0
  22. package/src/panels/builtin/shared.ts +1 -1
  23. package/src/panels/provider-account-snapshot.ts +1 -1
  24. package/src/panels/provider-accounts-panel.ts +23 -27
  25. package/src/panels/qr-panel.ts +182 -0
  26. package/src/panels/scrollable-list-panel.ts +407 -0
  27. package/src/panels/services-panel.ts +1 -1
  28. package/src/panels/subscription-panel.ts +1 -1
  29. package/src/panels/worktree-panel.ts +20 -19
  30. package/src/renderer/qr-renderer.ts +117 -0
  31. package/src/renderer/settings-modal-helpers.ts +122 -0
  32. package/src/renderer/settings-modal.ts +147 -111
  33. package/src/runtime/bootstrap-command-context.ts +1 -1
  34. package/src/runtime/bootstrap-command-parts.ts +31 -15
  35. package/src/runtime/bootstrap.ts +6 -1
  36. package/src/runtime/diagnostics/panels/index.ts +5 -5
  37. package/src/runtime/services.ts +1 -1
  38. package/src/runtime/store/domains/domain-read-matrix.ts +0 -2
  39. package/src/runtime/ui-events.ts +1 -46
  40. package/src/runtime/ui-read-model-helpers.ts +1 -32
  41. package/src/runtime/ui-read-models-observability-maintenance.ts +1 -81
  42. package/src/runtime/ui-read-models-observability-options.ts +1 -5
  43. package/src/runtime/ui-read-models-observability-remote.ts +1 -73
  44. package/src/runtime/ui-read-models-observability-security.ts +1 -172
  45. package/src/runtime/ui-read-models-observability-system.ts +1 -217
  46. package/src/runtime/ui-read-models-observability.ts +1 -59
  47. package/src/runtime/ui-service-queries.ts +1 -114
  48. package/src/version.ts +1 -1
  49. package/src/config/service-registry.ts +0 -1
  50. package/src/config/subscription-providers.ts +0 -1
  51. package/src/runtime/diagnostics/actions.ts +0 -776
  52. package/src/runtime/diagnostics/index.ts +0 -99
  53. package/src/runtime/diagnostics/panels/agents.ts +0 -252
  54. package/src/runtime/diagnostics/panels/events.ts +0 -188
  55. package/src/runtime/diagnostics/panels/health.ts +0 -242
  56. package/src/runtime/diagnostics/panels/tasks.ts +0 -251
  57. package/src/runtime/diagnostics/panels/tool-calls.ts +0 -267
  58. package/src/runtime/diagnostics/provider.ts +0 -262
  59. package/src/runtime/store/domains/conversation.ts +0 -1
  60. package/src/runtime/store/domains/permissions.ts +0 -1
  61. package/src/runtime/store/helpers/reducers/conversation.ts +0 -1
  62. package/src/runtime/store/helpers/reducers/lifecycle.ts +0 -1
  63. package/src/runtime/store/helpers/reducers/shared.ts +0 -60
  64. package/src/runtime/store/helpers/reducers/sync.ts +0 -555
  65. package/src/runtime/store/helpers/reducers.ts +0 -30
@@ -0,0 +1,407 @@
1
+ import type { Line } from '../types/grid.ts';
2
+ import { createEmptyLine } from '../types/grid.ts';
3
+ import { BasePanel } from './base-panel.ts';
4
+ import type { PanelCategory } from './types.ts';
5
+ import type { ComponentHealthMonitor } from '../runtime/perf/panel-health-monitor.ts';
6
+ import {
7
+ buildEmptyState,
8
+ buildPanelWorkspace,
9
+ DEFAULT_PANEL_PALETTE,
10
+ resolveScrollablePanelSection,
11
+ type PanelPalette,
12
+ } from './polish.ts';
13
+ import {
14
+ isPanelSearchBackspace,
15
+ isPanelSearchCancel,
16
+ isPanelSearchPrintable,
17
+ } from './search-focus.ts';
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // ScrollableListPanel<T>
21
+ // ---------------------------------------------------------------------------
22
+
23
+ /**
24
+ * Base class for all list-based panels that require scroll/cursor navigation.
25
+ *
26
+ * Subclasses implement:
27
+ * - `getItems()` — the ordered list of items to display
28
+ * - `renderItem(item, index, selected, width)` — one `Line` per item
29
+ *
30
+ * Optionally override:
31
+ * - `getEmptyStateMessage()` / `getEmptyStateActions()` — empty-state copy
32
+ * - `onSelect(item)` — called when the user presses Enter
33
+ * - `onAction(item, action)` — for secondary key bindings
34
+ * - `getPalette()` — colour palette (defaults to `DEFAULT_PANEL_PALETTE`)
35
+ * - `getPageSize()` — rows per page-up/page-down (default 10)
36
+ *
37
+ * `renderList()` produces the full `Line[]` output that a trivial panel's
38
+ * `render()` can return directly:
39
+ *
40
+ * ```ts
41
+ * render(width: number, height: number): Line[] {
42
+ * return this.renderList(width, height, { header: this.buildHeader(width) });
43
+ * }
44
+ * ```
45
+ */
46
+ export abstract class ScrollableListPanel<T> extends BasePanel {
47
+ protected selectedIndex = 0;
48
+ /** Tracks the first visible row index; kept in sync with resolveScrollablePanelSection. */
49
+ protected scrollStart = 0;
50
+
51
+ constructor(
52
+ id: string,
53
+ name: string,
54
+ icon: string,
55
+ category: PanelCategory,
56
+ componentHealthMonitor?: ComponentHealthMonitor,
57
+ ) {
58
+ super(id, name, icon, category, componentHealthMonitor);
59
+ }
60
+
61
+ // -------------------------------------------------------------------------
62
+ // Abstract — subclasses must implement
63
+ // -------------------------------------------------------------------------
64
+
65
+ /** Return the full ordered list of items to display. */
66
+ protected abstract getItems(): readonly T[];
67
+
68
+ /** Render a single item as one terminal `Line`. */
69
+ protected abstract renderItem(
70
+ item: T,
71
+ index: number,
72
+ selected: boolean,
73
+ width: number,
74
+ ): Line;
75
+
76
+ // -------------------------------------------------------------------------
77
+ // Optional overrides
78
+ // -------------------------------------------------------------------------
79
+
80
+ /** Short label shown in the empty-state title. */
81
+ protected getEmptyStateMessage(): string {
82
+ return 'No items';
83
+ }
84
+
85
+ /** Suggested actions shown in the empty state. */
86
+ protected getEmptyStateActions(): Array<{ command: string; summary: string }> {
87
+ return [];
88
+ }
89
+
90
+ /** Called when the user presses Enter on the selected item. */
91
+ protected onSelect(_item: T): void {}
92
+
93
+ /** Called for secondary key bindings (e.g. 'd' for delete). */
94
+ protected onAction(_item: T, _action: string): void {}
95
+
96
+ /** Colour palette used by `renderList()`. */
97
+ protected getPalette(): PanelPalette {
98
+ return DEFAULT_PANEL_PALETTE;
99
+ }
100
+
101
+ /**
102
+ * Rows to jump on pageup / pagedown.
103
+ * Override in `render()` to pass the actual visible row count:
104
+ *
105
+ * ```ts
106
+ * this._pageSize = Math.max(1, visibleRows - 2);
107
+ * ```
108
+ */
109
+ protected getPageSize(): number {
110
+ return 10;
111
+ }
112
+
113
+ // -------------------------------------------------------------------------
114
+ // Navigation — consistent across ALL panels
115
+ // -------------------------------------------------------------------------
116
+
117
+ handleInput(key: string): boolean {
118
+ const items = this.getItems();
119
+ const total = items.length;
120
+
121
+ switch (key) {
122
+ case 'up':
123
+ case 'k':
124
+ if (total === 0) return false;
125
+ this.selectedIndex = Math.max(0, this.selectedIndex - 1);
126
+ this.needsRender = true;
127
+ return true;
128
+
129
+ case 'down':
130
+ case 'j':
131
+ if (total === 0) return false;
132
+ this.selectedIndex = Math.min(total - 1, this.selectedIndex + 1);
133
+ this.needsRender = true;
134
+ return true;
135
+
136
+ case 'pageup':
137
+ if (total === 0) return false;
138
+ this.selectedIndex = Math.max(0, this.selectedIndex - this.getPageSize());
139
+ this.needsRender = true;
140
+ return true;
141
+
142
+ case 'pagedown':
143
+ if (total === 0) return false;
144
+ this.selectedIndex = Math.min(total - 1, this.selectedIndex + this.getPageSize());
145
+ this.needsRender = true;
146
+ return true;
147
+
148
+ case 'home':
149
+ case 'g':
150
+ if (total === 0) return false;
151
+ this.selectedIndex = 0;
152
+ this.needsRender = true;
153
+ return true;
154
+
155
+ case 'end':
156
+ case 'G':
157
+ if (total === 0) return false;
158
+ this.selectedIndex = total - 1;
159
+ this.needsRender = true;
160
+ return true;
161
+
162
+ case 'return':
163
+ case 'enter': {
164
+ if (total === 0) return false;
165
+ const item = items[this.selectedIndex];
166
+ if (item !== undefined) this.onSelect(item);
167
+ return true;
168
+ }
169
+
170
+ default:
171
+ return false;
172
+ }
173
+ }
174
+
175
+ // -------------------------------------------------------------------------
176
+ // Scroll state helpers
177
+ // -------------------------------------------------------------------------
178
+
179
+ /**
180
+ * Clamp `selectedIndex` to the current item count.
181
+ * Must be called after any data refresh that may shrink the list.
182
+ */
183
+ protected clampSelection(): void {
184
+ const total = this.getItems().length;
185
+ if (total === 0) {
186
+ this.selectedIndex = 0;
187
+ } else {
188
+ this.selectedIndex = Math.min(this.selectedIndex, total - 1);
189
+ }
190
+ }
191
+
192
+ // -------------------------------------------------------------------------
193
+ // Render helper — the main convenience entry point
194
+ // -------------------------------------------------------------------------
195
+
196
+ /**
197
+ * Render the full panel including optional header/footer and an empty state.
198
+ *
199
+ * Uses `resolveScrollablePanelSection` + `buildPanelWorkspace` internally,
200
+ * keeping `scrollStart` in sync after each call.
201
+ *
202
+ * @param width Panel width in columns.
203
+ * @param height Panel height in rows.
204
+ * @param options.header Lines prepended as the first workspace section.
205
+ * @param options.footer Lines appended as the last workspace section.
206
+ * @param options.emptyMessage Override for the empty-state title text.
207
+ * @param options.title Workspace title (defaults to `this.name`).
208
+ */
209
+ protected renderList(
210
+ width: number,
211
+ height: number,
212
+ options: {
213
+ readonly header?: readonly Line[];
214
+ readonly footer?: readonly Line[];
215
+ readonly emptyMessage?: string;
216
+ readonly title?: string;
217
+ } = {},
218
+ ): Line[] {
219
+ this.needsRender = false;
220
+ const palette = this.getPalette();
221
+ const items = this.getItems();
222
+ const title = options.title ?? this.name;
223
+
224
+ // Build all item lines (pre-render for resolveScrollablePanelSection)
225
+ const scrollableLines: Line[] = items.map((item, index) =>
226
+ this.renderItem(item, index, index === this.selectedIndex, width),
227
+ );
228
+
229
+ // Empty state
230
+ if (scrollableLines.length === 0) {
231
+ const emptyLines = buildEmptyState(
232
+ width,
233
+ options.emptyMessage ?? this.getEmptyStateMessage(),
234
+ '',
235
+ this.getEmptyStateActions(),
236
+ palette,
237
+ );
238
+ const lines = buildPanelWorkspace(width, height, {
239
+ title,
240
+ sections: [
241
+ ...(options.header ? [{ lines: options.header as Line[] }] : []),
242
+ { lines: emptyLines },
243
+ ...(options.footer ? [{ lines: options.footer as Line[] }] : []),
244
+ ],
245
+ palette,
246
+ });
247
+ while (lines.length < height) lines.push(createEmptyLine(width));
248
+ return lines.slice(0, height);
249
+ }
250
+
251
+ // Resolve scrollable section (updates scrollStart)
252
+ const beforeSections = options.header ? [{ lines: options.header as Line[] }] : [];
253
+ const afterSections = options.footer ? [{ lines: options.footer as Line[] }] : [];
254
+
255
+ const resolved = resolveScrollablePanelSection(width, height, {
256
+ palette,
257
+ beforeSections,
258
+ afterSections,
259
+ section: {
260
+ scrollableLines,
261
+ selectedIndex: this.selectedIndex,
262
+ scrollOffset: this.scrollStart,
263
+ guardRows: 1,
264
+ appendWindowSummary: scrollableLines.length > 5 ? { dimColor: palette.dim } : undefined,
265
+ },
266
+ });
267
+ this.scrollStart = resolved.scrollOffset;
268
+
269
+ const sections = [
270
+ ...beforeSections,
271
+ resolved.section,
272
+ ...afterSections,
273
+ ];
274
+
275
+ const lines = buildPanelWorkspace(width, height, {
276
+ title,
277
+ sections,
278
+ palette,
279
+ });
280
+ while (lines.length < height) lines.push(createEmptyLine(width));
281
+ return lines.slice(0, height);
282
+ }
283
+ }
284
+
285
+ // ---------------------------------------------------------------------------
286
+ // SearchableListPanel<T>
287
+ // ---------------------------------------------------------------------------
288
+
289
+ /**
290
+ * Extends `ScrollableListPanel<T>` with inline search/filter support.
291
+ *
292
+ * Subclasses implement:
293
+ * - `getAllItems()` — the full (unfiltered) item list
294
+ * - `matchesSearch(item, query)` — case-insensitive filter predicate
295
+ *
296
+ * `getItems()` is implemented here and returns filtered results. Do NOT
297
+ * override `getItems()` in subclasses — override `getAllItems()` instead.
298
+ *
299
+ * Search state:
300
+ * - Printable characters append to `searchQuery`.
301
+ * - Backspace/Delete removes the last character.
302
+ * - Escape clears the query.
303
+ * - Navigation keys (up/down/etc.) are forwarded to the parent.
304
+ *
305
+ * Render the search input line by calling `buildSearchInput(width)` from
306
+ * your panel's header builder.
307
+ */
308
+ export abstract class SearchableListPanel<T> extends ScrollableListPanel<T> {
309
+ protected searchQuery = '';
310
+
311
+ private _filteredItems: readonly T[] = [];
312
+ private _filterDirty = true;
313
+
314
+ // -------------------------------------------------------------------------
315
+ // Abstract — subclasses must implement
316
+ // -------------------------------------------------------------------------
317
+
318
+ /** Return the full unfiltered item list. */
319
+ protected abstract getAllItems(): readonly T[];
320
+
321
+ /** Return true if `item` matches the search `query`. */
322
+ protected abstract matchesSearch(item: T, query: string): boolean;
323
+
324
+ // -------------------------------------------------------------------------
325
+ // getItems — returns filtered list (do NOT override in subclasses)
326
+ // -------------------------------------------------------------------------
327
+
328
+ protected getItems(): readonly T[] {
329
+ if (this._filterDirty) {
330
+ const all = this.getAllItems();
331
+ this._filteredItems = this.searchQuery
332
+ ? all.filter((item) => this.matchesSearch(item, this.searchQuery))
333
+ : all;
334
+ this._filterDirty = false;
335
+ // Clamp after filter to keep selection in bounds
336
+ this.clampSelection();
337
+ }
338
+ return this._filteredItems;
339
+ }
340
+
341
+ /**
342
+ * Mark the filter cache as stale.
343
+ * Call this whenever `getAllItems()` returns new data.
344
+ */
345
+ protected invalidateFilter(): void {
346
+ this._filterDirty = true;
347
+ this.needsRender = true;
348
+ }
349
+
350
+ // -------------------------------------------------------------------------
351
+ // Input — search first, navigation second
352
+ // -------------------------------------------------------------------------
353
+
354
+ handleInput(key: string): boolean {
355
+ // Backspace: trim query
356
+ if (isPanelSearchBackspace(key)) {
357
+ if (this.searchQuery.length > 0) {
358
+ this.searchQuery = this.searchQuery.slice(0, -1);
359
+ this._filterDirty = true;
360
+ this.needsRender = true;
361
+ return true;
362
+ }
363
+ return false;
364
+ }
365
+
366
+ // Escape: clear query
367
+ if (isPanelSearchCancel(key)) {
368
+ if (this.searchQuery.length > 0) {
369
+ this.searchQuery = '';
370
+ this._filterDirty = true;
371
+ this.needsRender = true;
372
+ return true;
373
+ }
374
+ return false;
375
+ }
376
+
377
+ // Printable characters: append to query
378
+ if (isPanelSearchPrintable(key)) {
379
+ this.searchQuery += key;
380
+ this._filterDirty = true;
381
+ this.needsRender = true;
382
+ return true;
383
+ }
384
+
385
+ // Navigation and Enter: delegate to parent
386
+ return super.handleInput(key);
387
+ }
388
+
389
+ /**
390
+ * Build the search input `Line` suitable for use in a panel header.
391
+ *
392
+ * Import `buildSearchInputLine` from `./polish.ts` and call it with
393
+ * `this.searchQuery`. Convenience wrapper:
394
+ *
395
+ * ```ts
396
+ * import { buildSearchInputLine } from './polish.ts';
397
+ *
398
+ * private buildHeader(width: number): Line[] {
399
+ * return [buildSearchInputLine(width, 'Filter', this.searchQuery, this.getPalette(), {})];
400
+ * }
401
+ * ```
402
+ *
403
+ * This method is intentionally left as a documentation reference rather
404
+ * than a concrete implementation to avoid coupling the base class to a
405
+ * specific label or search-input layout.
406
+ */
407
+ }
@@ -5,7 +5,7 @@ import {
5
5
  type ServiceConfig,
6
6
  type ServiceInspection,
7
7
  type ServiceConnectionTestResult,
8
- } from '../config/service-registry.ts';
8
+ } from '@pellux/goodvibes-sdk/platform/config/service-registry';
9
9
  import type { ServiceInspectionQuery, SubscriptionAccessQuery } from '../runtime/ui-service-queries.ts';
10
10
  import {
11
11
  buildEmptyState,
@@ -2,7 +2,7 @@ import type { Line } from '../types/grid.ts';
2
2
  import { createEmptyLine } from '../types/grid.ts';
3
3
  import { BasePanel } from './base-panel.ts';
4
4
  import type { ProviderSubscription, PendingSubscriptionLogin } from '@pellux/goodvibes-sdk/platform/config/subscriptions';
5
- import { listBuiltinSubscriptionProviders } from '../config/subscription-providers.ts';
5
+ import { listBuiltinSubscriptionProviders } from '@pellux/goodvibes-sdk/platform/config/subscription-providers';
6
6
  import type { ServiceInspectionQuery, SubscriptionAccessQuery } from '../runtime/ui-service-queries.ts';
7
7
  import {
8
8
  buildDetailBlock,
@@ -1,6 +1,6 @@
1
1
  import type { Line } from '../types/grid.ts';
2
2
  import { createEmptyLine } from '../types/grid.ts';
3
- import { BasePanel } from './base-panel.ts';
3
+ import { ScrollableListPanel } from './scrollable-list-panel.ts';
4
4
  import { buildKeyValueLine, buildPanelLine, buildPanelWorkspace, DEFAULT_PANEL_PALETTE, resolvePrimaryScrollableSection, type PanelWorkspaceSection } from './polish.ts';
5
5
  import { summarizeWorktreeOwnership, type WorktreeRegistry, type WorktreeStatusRecord } from '@pellux/goodvibes-sdk/platform/runtime/worktree/registry';
6
6
 
@@ -22,10 +22,8 @@ function stateColor(state: WorktreeStatusRecord['state']): string {
22
22
  }
23
23
  }
24
24
 
25
- export class WorktreePanel extends BasePanel {
25
+ export class WorktreePanel extends ScrollableListPanel<WorktreeStatusRecord> {
26
26
  private rows: WorktreeStatusRecord[] = [];
27
- private selectedIndex = 0;
28
- private scrollOffset = 0;
29
27
  private loading = false;
30
28
  private readonly worktreeRegistry: WorktreeRegistry;
31
29
 
@@ -45,18 +43,21 @@ export class WorktreePanel extends BasePanel {
45
43
  void this.refresh();
46
44
  return true;
47
45
  }
48
- if (this.rows.length === 0) return false;
49
- if (key === 'up' || key === 'k') {
50
- this.selectedIndex = Math.max(0, this.selectedIndex - 1);
51
- this.markDirty();
52
- return true;
53
- }
54
- if (key === 'down' || key === 'j') {
55
- this.selectedIndex = Math.min(this.rows.length - 1, this.selectedIndex + 1);
56
- this.markDirty();
57
- return true;
58
- }
59
- return false;
46
+ return super.handleInput(key);
47
+ }
48
+
49
+ protected getItems(): readonly WorktreeStatusRecord[] {
50
+ return this.rows;
51
+ }
52
+
53
+ protected renderItem(row: WorktreeStatusRecord, index: number, _selected: boolean, width: number): Line {
54
+ const bg = index === this.selectedIndex ? C.headerBg : undefined;
55
+ return buildPanelLine(width, [
56
+ [` ${row.kind}`.padEnd(14), C.info, bg],
57
+ [` ${row.state}`.padEnd(16), stateColor(row.state), bg],
58
+ [` ${row.branch}`.padEnd(24), C.value, bg],
59
+ [` ${row.path}`.slice(0, Math.max(0, width - 56)), C.dim, bg],
60
+ ]);
60
61
  }
61
62
 
62
63
  private async refresh(): Promise<void> {
@@ -64,7 +65,7 @@ export class WorktreePanel extends BasePanel {
64
65
  this.markDirty();
65
66
  try {
66
67
  this.rows = await this.worktreeRegistry.list();
67
- this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.rows.length - 1));
68
+ this.clampSelection();
68
69
  } finally {
69
70
  this.loading = false;
70
71
  this.markDirty();
@@ -155,14 +156,14 @@ export class WorktreePanel extends BasePanel {
155
156
  ]);
156
157
  }),
157
158
  selectedIndex: this.selectedIndex,
158
- scrollOffset: this.scrollOffset,
159
+ scrollOffset: this.scrollStart,
159
160
  guardRows: 1,
160
161
  minRows: 4,
161
162
  appendWindowSummary: { dimColor: C.dim },
162
163
  },
163
164
  afterSections: [detailSection],
164
165
  });
165
- this.scrollOffset = resolvedWorktreesSection.scrollOffset;
166
+ this.scrollStart = resolvedWorktreesSection.scrollOffset;
166
167
  sections.push(resolvedWorktreesSection.section);
167
168
  sections.push(detailSection);
168
169
  }
@@ -0,0 +1,117 @@
1
+ import type { Line } from '../types/grid.ts';
2
+ import { createEmptyLine, createStyledCell } from '../types/grid.ts';
3
+ import { getDisplayWidth } from '../utils/terminal-width.ts';
4
+ import { generateQrMatrix } from '@pellux/goodvibes-sdk/platform/pairing/qr-generator';
5
+
6
+ export { generateQrMatrix };
7
+
8
+ /**
9
+ * Render a QR boolean matrix to terminal Lines using Unicode half-block characters.
10
+ *
11
+ * Two matrix rows map to one terminal row:
12
+ * top=dark, bottom=dark → '█' (FULL BLOCK)
13
+ * top=dark, bottom=light → '▀' (UPPER HALF BLOCK)
14
+ * top=light, bottom=dark → '▄' (LOWER HALF BLOCK)
15
+ * top=light, bottom=light → ' ' (SPACE)
16
+ *
17
+ * @param modules - 2D boolean matrix where true = dark module
18
+ * @param width - Terminal width available for centering
19
+ * @param options - Optional fg/bg overrides
20
+ */
21
+ export function renderQrMatrix(
22
+ modules: readonly boolean[][],
23
+ width: number,
24
+ options?: { fg?: string; bg?: string },
25
+ ): Line[] {
26
+ const fg = options?.fg ?? '#000000';
27
+ const bg = options?.bg ?? '#ffffff';
28
+
29
+ const rows = modules.length;
30
+ const cols = modules[0]?.length ?? 0;
31
+ if (rows === 0 || cols === 0) return [];
32
+
33
+ // Each terminal row covers two matrix rows
34
+ const terminalRows = Math.ceil(rows / 2);
35
+ // Left-align with a single-cell indent. Visually aligns with the text above
36
+ // the QR when rendered with half-block characters; bumping higher
37
+ // mis-registers the finder patterns by a visible unit.
38
+ const leftPad = 1;
39
+
40
+ const lines: Line[] = [];
41
+
42
+ // Prepend a single-row top quiet band of bg so the QR's first module row
43
+ // does not butt up against whatever chrome precedes it. Combined with the
44
+ // leftPad=1 on the horizontal axis, this keeps the finder-pattern square
45
+ // margin consistent on both axes.
46
+ {
47
+ const topBand = createEmptyLine(width);
48
+ const endCol = Math.min(leftPad + cols + 1, width);
49
+ for (let col = 0; col < endCol; col++) {
50
+ topBand[col] = createStyledCell(' ', { fg, bg });
51
+ }
52
+ lines.push(topBand);
53
+ }
54
+
55
+ for (let termRow = 0; termRow < terminalRows; termRow++) {
56
+ const matrixRowTop = termRow * 2;
57
+ const matrixRowBot = termRow * 2 + 1;
58
+ const topRow = modules[matrixRowTop];
59
+ const botRow = matrixRowBot < rows ? modules[matrixRowBot] : null;
60
+
61
+ const line = createEmptyLine(width);
62
+
63
+ // Fill leading padding with bg
64
+ for (let col = 0; col < leftPad && col < width; col++) {
65
+ line[col] = createStyledCell(' ', { fg, bg });
66
+ }
67
+
68
+ // Render QR columns
69
+ for (let col = 0; col < cols; col++) {
70
+ const termCol = leftPad + col;
71
+ if (termCol >= width) break;
72
+
73
+ const topDark = topRow ? (topRow[col] ?? false) : false;
74
+ const botDark = botRow ? (botRow[col] ?? false) : false;
75
+
76
+ let char: string;
77
+ let cellFg: string;
78
+ let cellBg: string;
79
+
80
+ if (topDark && botDark) {
81
+ char = '█';
82
+ cellFg = fg;
83
+ cellBg = bg;
84
+ } else if (topDark && !botDark) {
85
+ char = '▀';
86
+ cellFg = fg;
87
+ cellBg = bg;
88
+ } else if (!topDark && botDark) {
89
+ char = '▄';
90
+ cellFg = fg;
91
+ cellBg = bg;
92
+ } else {
93
+ char = ' ';
94
+ cellFg = fg;
95
+ cellBg = bg;
96
+ }
97
+
98
+ // Some terminals may not render block chars at full width — guard
99
+ const charWidth = getDisplayWidth(char);
100
+ if (charWidth <= 0) {
101
+ line[termCol] = createStyledCell(' ', { fg: cellFg, bg: cellBg });
102
+ } else {
103
+ line[termCol] = createStyledCell(char, { fg: cellFg, bg: cellBg });
104
+ }
105
+ }
106
+
107
+ // Fill trailing with bg up to end of QR block
108
+ for (let col = leftPad + cols; col < leftPad + cols + 1 && col < width; col++) {
109
+ line[col] = createStyledCell(' ', { fg, bg });
110
+ }
111
+
112
+ lines.push(line);
113
+ }
114
+
115
+ return lines;
116
+ }
117
+