pi-odd-worktree 3.10.0 → 3.11.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.
@@ -0,0 +1,963 @@
1
+ 'use strict';
2
+ // The user's own prompt, drawn as a card on this package's substrate: while the bridge's
3
+ // `Card activity` line answers this package's activity design, `UserMessageComponent.render`
4
+ // answers the card instead of Pi's plain block; for every other answer, and for every shape
5
+ // it cannot read, the host's own rows come back byte for byte.
6
+ //
7
+ // Everything below observes the public seam: the shim is installed on a STUB class exactly as
8
+ // the extension installs it on Pi's, the bridge is the published object a process-wide slot
9
+ // holds, the style is the slot Gentle Shell writes, and the rows are read by calling `render`
10
+ // on the component — the same call the host makes on every frame.
11
+ const assert = require('node:assert/strict');
12
+ const { after, afterEach, beforeEach, test } = require('node:test');
13
+ const fs = require('node:fs');
14
+ const os = require('node:os');
15
+ const path = require('node:path');
16
+ const { pathToFileURL } = require('node:url');
17
+
18
+ const { installUserPromptCard, uninstallUserPromptCard } = require('../lib/user-prompt-card.js');
19
+ const { CARD_STYLE, CARD_STYLE_SLOT } = require('../lib/card-style.js');
20
+ // The extension itself, loaded the way `tools/fixtures/load-extension.js` loads it: the deferred
21
+ // install's guard lives there, so the test has to reach the module's own seam.
22
+ const fixture = require('./fixtures/load-extension.js');
23
+
24
+ const BRIDGE_API_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
25
+ const ACTIVITY = 'odd-worktree.bash-activity';
26
+ const OTHER_DESIGN = 'acme.tools';
27
+
28
+ // ---- the theme: one role per painted cell ----
29
+ //
30
+ // The card paints a theme ROLE, never a colour, so the stub turns each role into a distinct
31
+ // SGR code. A row can then be read back cell by cell (`cells`), which is how "every chrome
32
+ // cell wears the accent" and "no user-message background is left anywhere" are asserted
33
+ // without reading any internal state.
34
+ const ROLE_CODE = { accent: '35', border: '34', text: '37', dim: '2', muted: '90', success: '32', warning: '33', error: '31' };
35
+ const BG_CODE = { toolSuccessBg: '48;5;240', toolPendingBg: '48;5;214', toolErrorBg: '48;5;203' };
36
+ const MARKDOWN_CODE = '36';
37
+ const USER_MESSAGE_BG_CODE = '48;5;236';
38
+
39
+ function roleTheme() {
40
+ const roles = [];
41
+ return {
42
+ roles,
43
+ fg(role, text) {
44
+ roles.push(role);
45
+ return `\x1b[${ROLE_CODE[role] ?? '39'}m${text}\x1b[39m`;
46
+ },
47
+ bg(role, text) {
48
+ roles.push(`bg:${role}`);
49
+ return `\x1b[${BG_CODE[role] ?? '49'}m${text}\x1b[49m`;
50
+ },
51
+ };
52
+ }
53
+
54
+ const plainTheme = { fg: (_role, value) => value };
55
+ // The float style paints its band through the theme's own `bg`; a theme without one keeps the
56
+ // neon outline (`lib/shell-card.js`), so the two style claims below need a band-capable theme.
57
+ const bandTheme = { fg: (_role, value) => value, bg: (_role, value) => `\x1b[48;5;240m${value}\x1b[49m` };
58
+ const taggedTheme = { fg: (role, value) => `<${role}>${value}</${role}>` };
59
+
60
+ // Pi's prompt-zone markers, exactly as `UserMessageComponent.render` writes them: the start of
61
+ // the zone on the first row, its end and its final marker on the last. They are OSC sequences,
62
+ // not SGR paint, so they are zero width and every helper below strips them as such.
63
+ const OSC133_ZONE_START = '\x1b]133;A\x07';
64
+ const OSC133_ZONE_END = '\x1b]133;B\x07';
65
+ const OSC133_ZONE_FINAL = '\x1b]133;C\x07';
66
+ const OSC133_ZONE_CLOSE = OSC133_ZONE_END + OSC133_ZONE_FINAL;
67
+
68
+ const ANSI = /\x1b\[[0-9;]*m/g;
69
+ const OSC = /\x1b\][^\x07]*\x07/g;
70
+ const stripAnsi = (value) => value.replace(ANSI, '').replace(OSC, '');
71
+ const chars = (value) => [...stripAnsi(value)];
72
+ const unpaint = (value) => stripAnsi(value).replace(/<\/?[a-zA-Z][a-zA-Z0-9]*>/g, '');
73
+
74
+ /** One row as `{ char, code }` cells: the SGR in force when each visible character was drawn. */
75
+ function cells(row) {
76
+ const SGR = /\x1b\[([0-9;]*)m/y;
77
+ const ZONE = /\x1b\][^\x07]*\x07/y;
78
+ const out = [];
79
+ let code = '0';
80
+ let index = 0;
81
+ while (index < row.length) {
82
+ SGR.lastIndex = index;
83
+ const match = SGR.exec(row);
84
+ if (match !== null) {
85
+ code = match[1];
86
+ index = SGR.lastIndex;
87
+ continue;
88
+ }
89
+ // An OSC sequence is a marker, not a cell: no column, no role.
90
+ ZONE.lastIndex = index;
91
+ if (ZONE.exec(row) !== null) {
92
+ index = ZONE.lastIndex;
93
+ continue;
94
+ }
95
+ out.push({ char: row[index], code });
96
+ index += 1;
97
+ }
98
+ return out;
99
+ }
100
+
101
+ // ---- the measurement seam (the one `tools/message-card.test.js` uses, ANSI preserved) ----
102
+
103
+ function makeMetrics(counts) {
104
+ const bump = (name) => {
105
+ if (counts !== undefined) counts[name] += 1;
106
+ };
107
+ return {
108
+ visibleWidth(value) {
109
+ bump('visibleWidth');
110
+ return chars(value).length;
111
+ },
112
+ truncateToWidth(value, width, ellipsis = '') {
113
+ bump('truncateToWidth');
114
+ if (width <= 0) return '';
115
+ if (chars(value).length <= width) return value;
116
+ const tail = ellipsis ?? '';
117
+ const plain = [...stripAnsi(value)];
118
+ return plain.slice(0, Math.max(0, width - [...tail].length)).join('') + tail;
119
+ },
120
+ wrapTextWithAnsi(value, width) {
121
+ bump('wrapTextWithAnsi');
122
+ if (width <= 0) return [value];
123
+ if (chars(value).length <= width) return [value];
124
+ const rows = [];
125
+ let current = '';
126
+ for (const word of stripAnsi(value).split(' ')) {
127
+ const candidate = current === '' ? word : `${current} ${word}`;
128
+ if ([...candidate].length <= width) {
129
+ current = candidate;
130
+ continue;
131
+ }
132
+ if (current !== '') rows.push(current);
133
+ current = word;
134
+ }
135
+ rows.push(current);
136
+ return rows;
137
+ },
138
+ };
139
+ }
140
+
141
+ const metrics = makeMetrics();
142
+ const countingMetrics = () => {
143
+ const counts = { visibleWidth: 0, truncateToWidth: 0, wrapTextWithAnsi: 0 };
144
+ return { counts, metrics: makeMetrics(counts) };
145
+ };
146
+
147
+ // ---- the stub host: Pi's `UserMessageComponent` and its Markdown child ----
148
+
149
+ const markdownTheme = { heading: (text) => text, code: (text) => text };
150
+
151
+ /** Pi's Markdown, as the card sees it: the constructor takes the six arguments Pi passes. */
152
+ class StubMarkdown {
153
+ constructor(text, paddingX, paddingY, theme, defaultTextStyle, options) {
154
+ this.text = text;
155
+ this.paddingX = paddingX;
156
+ this.paddingY = paddingY;
157
+ this.theme = theme;
158
+ // Pi's MarkdownTheme is captured when the child is BUILT: a theme switched later is
159
+ // visible to a freshly built child and invisible to this one, exactly like Pi's own.
160
+ this.code = StubMarkdown.code;
161
+ this.defaultTextStyle = defaultTextStyle;
162
+ this.options = options;
163
+ StubMarkdown.made.push(this);
164
+ }
165
+
166
+ render(width) {
167
+ this.widths = [...(this.widths ?? []), width];
168
+ // A renderer that refuses the document: the card must answer the host's own rows.
169
+ if (this.text === 'THROW') throw new Error('the renderer blew up');
170
+ if (this.text === 'NOT_ROWS') return 'not rows';
171
+ if (this.text === 'EMPTY_BODY') return [];
172
+ // Rows the renderer already painted: the card must PLACE them, never repaint them.
173
+ const lines = String(this.text).split('\n').map((line) => `\x1b[${this.code}m${line}\x1b[39m`);
174
+ // Pi's Markdown pads its content with `paddingY` blank rows above and below
175
+ // (`emptyLines.concat(contentLines, emptyLines)`), and the stub models that: a clone that
176
+ // keeps the host's padding costs the terminal two rows per prompt.
177
+ const blank = ' '.repeat(Math.max(0, width));
178
+ const pad = Array.from({ length: this.paddingY }, () => blank);
179
+ return [...pad, ...lines, ...pad];
180
+ }
181
+ }
182
+ StubMarkdown.made = [];
183
+ StubMarkdown.code = MARKDOWN_CODE;
184
+
185
+ /** Pi's user message: a `Container` whose one child is the Markdown the card rebuilds. */
186
+ class UserMessageComponent {
187
+ constructor(text, options = {}) {
188
+ this.text = text;
189
+ this.outputPad = 1;
190
+ this.empty = options.empty === true;
191
+ this.children = options.children !== undefined
192
+ ? options.children
193
+ : [new StubMarkdown(
194
+ text,
195
+ options.paddingX ?? 1,
196
+ 1,
197
+ options.markdownTheme !== undefined ? options.markdownTheme : markdownTheme,
198
+ { color: (content) => `\x1b[37m${content}\x1b[39m`, bgColor: (content) => `\x1b[${USER_MESSAGE_BG_CODE}m${content}\x1b[49m` },
199
+ options.markdownOptions ?? { preserveOrderedListMarkers: true, preserveBackslashEscapes: true },
200
+ )];
201
+ }
202
+
203
+ // Pi's own block, in Pi's own shape: the card either replaces it whole or leaves it alone,
204
+ // with the prompt-zone markers on its first and last row in Pi's OWN order — `start`
205
+ // prefixed on the first row, `end` then `final` prefixed on the last
206
+ // (`user-message.js`: `last = OSC133_ZONE_END + OSC133_ZONE_FINAL + last`).
207
+ render(width) {
208
+ if (this.empty) return [];
209
+ const lines = [`\x1b[2mnative ${width}\x1b[22m`, `native ${this.text}`];
210
+ const zoned = [...lines];
211
+ zoned[0] = OSC133_ZONE_START + zoned[0];
212
+ zoned[zoned.length - 1] = OSC133_ZONE_CLOSE + zoned[zoned.length - 1];
213
+ return zoned;
214
+ }
215
+ }
216
+
217
+ // Pi's own rows, called through the function the shim wraps: the byte-for-byte reference.
218
+ const NATIVE_RENDER = UserMessageComponent.prototype.render;
219
+ const nativeRows = (component, width) => NATIVE_RENDER.call(component, width);
220
+
221
+ const PROMPT = ['explain the card', 'and keep `this` visible'].join('\n');
222
+
223
+ function promptComponent(text = PROMPT) {
224
+ return new UserMessageComponent(text);
225
+ }
226
+
227
+ // ---- the published bridge, and the slots the runtime reads ----
228
+
229
+ function publishBridge(answer) {
230
+ const state = { answer, calls: [] };
231
+ globalThis[BRIDGE_API_SLOT] = {
232
+ schema: 'gentle-shell-bridge/api',
233
+ version: 1,
234
+ resolveToolDesignSelection(tool) {
235
+ state.calls.push(tool);
236
+ const value = state.answer;
237
+ if (value instanceof Error) throw value;
238
+ if (typeof value === 'function') return value(tool);
239
+ return value;
240
+ },
241
+ };
242
+ return state;
243
+ }
244
+
245
+ const ACTIVITY_ANSWER = { kind: 'design', design: { id: ACTIVITY } };
246
+
247
+ function install(options = {}) {
248
+ const seams = options.seams ?? {};
249
+ const component = options.component ?? UserMessageComponent;
250
+ return installUserPromptCard({
251
+ component,
252
+ metrics: seams.metrics ?? (() => (seams.counting === undefined ? metrics : seams.counting)),
253
+ theme: seams.theme ?? (() => (seams.paint === undefined ? plainTheme : seams.paint)),
254
+ });
255
+ }
256
+
257
+ beforeEach(() => {
258
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
259
+ StubMarkdown.made = [];
260
+ StubMarkdown.code = MARKDOWN_CODE;
261
+ });
262
+ afterEach(() => {
263
+ uninstallUserPromptCard();
264
+ delete globalThis[BRIDGE_API_SLOT];
265
+ delete globalThis[CARD_STYLE_SLOT];
266
+ });
267
+ after(() => {
268
+ uninstallUserPromptCard();
269
+ delete globalThis[BRIDGE_API_SLOT];
270
+ delete globalThis[CARD_STYLE_SLOT];
271
+ });
272
+
273
+ // ---- S1: the card, and only while the line answers this package's design ----
274
+
275
+ test('while Card activity answers activity the prompt is a card headed ✿ You', () => {
276
+ const bridge = publishBridge(ACTIVITY_ANSWER);
277
+ const outcome = install();
278
+ assert.equal(outcome.installed, true);
279
+ const component = promptComponent();
280
+ const rows = component.render(60);
281
+ assert.notDeepEqual(rows, nativeRows(component, 60), 'the card replaces Pi\'s own block');
282
+ const head = unpaint(rows[0]);
283
+ assert.match(head, /^╭─ ✿ You /u, 'the first design: the dead-flower mark and the name, on the frame');
284
+ assert.equal(unpaint(rows[rows.length - 1]).startsWith('╰'), true, 'the frame is closed by a rule');
285
+ assert.ok(rows.some((row) => unpaint(row).includes('explain the card')), 'the prompt is the body');
286
+ assert.ok(rows.some((row) => unpaint(row).includes('and keep `this` visible')), 'every row of it is drawn');
287
+ assert.deepEqual(bridge.calls, ['bash'], 'the question is the bash line every other card asks');
288
+ for (const row of rows) assert.equal(chars(row).length, 60, `"${unpaint(row)}" is 60 wide`);
289
+ });
290
+
291
+ test('every other answer, an absent reader or a throwing one hands Pi\'s own rows back byte for byte', () => {
292
+ const cases = [
293
+ ['the host\'s own value', () => ({ kind: 'native' })],
294
+ ['another plugin\'s design', () => ({ kind: 'design', design: { id: OTHER_DESIGN } })],
295
+ ['a design with no id', () => ({ kind: 'design', design: {} })],
296
+ ['a design that has left the line', () => ({ kind: 'missing' })],
297
+ ['a line that covers nothing', () => ({ kind: 'not-covered' })],
298
+ ['an answer nothing can read', () => undefined],
299
+ ['a reader that throws', () => new Error('the bridge blew up')],
300
+ ['no published bridge at all', () => null],
301
+ ['an object that is not a bridge', () => 'native'],
302
+ ];
303
+ install();
304
+ for (const [name, answer] of cases) {
305
+ if (answer === null) delete globalThis[BRIDGE_API_SLOT];
306
+ else globalThis[BRIDGE_API_SLOT] = { schema: 'gentle-shell-bridge/api', version: 1, resolveToolDesignSelection: answer };
307
+ const component = promptComponent();
308
+ const expected = nativeRows(component, 60);
309
+ assert.deepEqual(component.render(60), expected, name);
310
+ if (answer !== null) {
311
+ delete globalThis[BRIDGE_API_SLOT].resolveToolDesignSelection;
312
+ assert.deepEqual(component.render(60), expected, `${name}: no reader member on the object`);
313
+ }
314
+ }
315
+ });
316
+
317
+ test('a bridge the runtime cannot read is not a bridge: the schema and version gate is the same one', () => {
318
+ install();
319
+ for (const api of [
320
+ { schema: 'gentle-shell-bridge/api', version: 2, resolveToolDesignSelection: () => ACTIVITY_ANSWER },
321
+ { schema: 'other/api', version: 1, resolveToolDesignSelection: () => ACTIVITY_ANSWER },
322
+ null,
323
+ ]) {
324
+ globalThis[BRIDGE_API_SLOT] = api;
325
+ const component = promptComponent();
326
+ assert.deepEqual(component.render(60), nativeRows(component, 60));
327
+ }
328
+ });
329
+
330
+ // ---- S2: the gate is read per paint, never cached ----
331
+
332
+ test('flipping Card activity repaints the same mounted component, with no re-install', () => {
333
+ const bridge = publishBridge(ACTIVITY_ANSWER);
334
+ install();
335
+ const component = promptComponent();
336
+ const card = component.render(60);
337
+ assert.match(unpaint(card[0]), /^╭─ ✿ You /u, 'on');
338
+ bridge.answer = { kind: 'native' };
339
+ assert.deepEqual(component.render(60), nativeRows(component, 60), 'off: Pi\'s own rows, byte for byte');
340
+ bridge.answer = ACTIVITY_ANSWER;
341
+ assert.deepEqual(component.render(60), card, 'on again, the same card');
342
+ assert.equal(bridge.calls.length, 3, 'the line was asked on every one of the three paints');
343
+ });
344
+
345
+ test('a width too small to draw a frame hands the rows straight back', () => {
346
+ publishBridge(ACTIVITY_ANSWER);
347
+ install();
348
+ const component = promptComponent();
349
+ for (const width of [0, 1, 4, 5]) {
350
+ assert.deepEqual(component.render(width), nativeRows(component, width), `width ${width}`);
351
+ }
352
+ assert.notDeepEqual(component.render(6), nativeRows(component, 6), 'a usable width still paints');
353
+ });
354
+
355
+ // ---- S3/S4: the accent frame in both styles, the body untouched ----
356
+
357
+ const FRAME_CHARS = new Set(['╭', '╮', '╰', '╯', '─', '│', '▎']);
358
+
359
+ function assertAccentChrome(rows, style) {
360
+ const frame = rows.flatMap((row) => cells(row)).filter((cell) => FRAME_CHARS.has(cell.char));
361
+ assert.ok(frame.length > 0, `${style}: the card draws a frame`);
362
+ for (const cell of frame) {
363
+ assert.equal(cell.code, ROLE_CODE.accent, `${style}: "${cell.char}" is painted in the accent role`);
364
+ }
365
+ const body = rows.flatMap((row) => cells(row)).filter((cell) => cell.code === MARKDOWN_CODE);
366
+ assert.ok(body.length > 0, `${style}: the body keeps the paint its own renderer gave it`);
367
+ assert.equal(
368
+ rows.flatMap((row) => cells(row)).some((cell) => cell.code === USER_MESSAGE_BG_CODE),
369
+ false,
370
+ `${style}: nothing keeps the user message's background`,
371
+ );
372
+ }
373
+
374
+ test('in neon the whole frame and the name wear the accent, and the body keeps its own paint', () => {
375
+ publishBridge(ACTIVITY_ANSWER);
376
+ const paint = roleTheme();
377
+ install({ seams: { paint } });
378
+ const component = promptComponent();
379
+ const rows = component.render(60);
380
+ assert.match(unpaint(rows[0]), /^╭─ ✿ You /u);
381
+ assertAccentChrome(rows, 'neon');
382
+ const head = cells(rows[0]);
383
+ const mark = head.find((cell) => cell.char === '✿');
384
+ assert.equal(mark.code, ROLE_CODE.accent, 'the mark wears the title role');
385
+ for (const letter of ['Y', 'o', 'u']) {
386
+ const cell = head.find((candidate) => candidate.char === letter);
387
+ assert.equal(cell.code, ROLE_CODE.accent, `"${letter}" of the name wears the accent`);
388
+ }
389
+ assert.equal(paint.roles.includes('text'), false, 'no body row is repainted in the body role');
390
+ assert.equal(paint.roles.some((role) => role.startsWith('bg:userMessage')), false, 'the user message background is never painted');
391
+ });
392
+
393
+ test('in float the whole rail wears the accent too, and the band is the card\'s own', () => {
394
+ publishBridge(ACTIVITY_ANSWER);
395
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.FLOAT;
396
+ const paint = roleTheme();
397
+ install({ seams: { paint } });
398
+ const component = promptComponent();
399
+ const rows = component.render(60);
400
+ // Float pads one blank band row above the heading, so the heading is found, not assumed first.
401
+ assert.ok(rows.some((row) => /^\s*▎ ✿ You /u.test(unpaint(row))), 'the rail style, with the same mark and name');
402
+ assert.match(unpaint(rows[0]), /^\s*▎/u, 'the band opens with the rail');
403
+ assert.doesNotMatch(rows.map(unpaint).join('\n'), /[╭╮╰╯]/u, 'no neon corner survives a float card');
404
+ assertAccentChrome(rows, 'float');
405
+ assert.equal(paint.roles.includes('bg:userMessageBg'), false, 'the user message background is never painted');
406
+ const rails = rows.flatMap((row) => cells(row)).filter((cell) => cell.char === '▎');
407
+ assert.ok(rails.length >= 3, 'the heading, the body and the closing rail are all drawn');
408
+ for (const row of rows) assert.equal(chars(row).length, 60, `"${unpaint(row)}" is 60 wide`);
409
+ });
410
+
411
+ test('a mid-session style flip repaints a prompt already on screen, in both directions', () => {
412
+ publishBridge(ACTIVITY_ANSWER);
413
+ install({ seams: { paint: bandTheme } });
414
+ const component = promptComponent();
415
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
416
+ const neon = unpaint(component.render(60)[0]);
417
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.FLOAT;
418
+ const float = unpaint(component.render(60)[0]);
419
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
420
+ const back = unpaint(component.render(60)[0]);
421
+ assert.match(neon, /^╭─/u);
422
+ assert.match(float, /^\s*▎/u);
423
+ assert.match(back, /^╭─/u);
424
+ });
425
+
426
+ test('the prompt is never capped: every row of a long message is drawn', () => {
427
+ publishBridge(ACTIVITY_ANSWER);
428
+ install();
429
+ const body = Array.from({ length: 12 }, (_unused, index) => `row ${index + 1} of the prompt`);
430
+ const rows = promptComponent(body.join('\n')).render(60).map(unpaint);
431
+ for (const line of body) assert.ok(rows.some((row) => row.includes(line)), `"${line}" is drawn`);
432
+ });
433
+
434
+ // ---- S5: the body is Pi's own Markdown, rebuilt without the background ----
435
+
436
+ test('the body rows are the child\'s own Markdown rebuilt with no background and no side padding', () => {
437
+ publishBridge(ACTIVITY_ANSWER);
438
+ install();
439
+ const component = promptComponent();
440
+ const original = component.children[0];
441
+ component.render(60);
442
+ assert.equal(StubMarkdown.made.length, 2, 'one clone, built from the child\'s own constructor');
443
+ const clone = StubMarkdown.made[1];
444
+ assert.notEqual(clone, original);
445
+ assert.equal(clone.constructor, original.constructor);
446
+ assert.equal(clone.text, original.text, 'the prompt itself');
447
+ assert.equal(clone.paddingX, 0, 'no side padding: the card frames it');
448
+ assert.equal(clone.paddingY, 0, 'no vertical padding either: the frame is the spacing, as in the file cards');
449
+ assert.equal(clone.theme, original.theme, 'the host\'s own Markdown theme');
450
+ assert.equal(clone.options, original.options, 'the host\'s own options, so markers and transformers keep working');
451
+ assert.equal(clone.defaultTextStyle.bgColor, undefined, 'the user message background is dropped');
452
+ assert.equal(typeof clone.defaultTextStyle.color, 'function', 'the text colour is the body\'s own paint');
453
+ });
454
+
455
+ test('a steady frame rebuilds nothing, and a width change or a style flip redraws', () => {
456
+ publishBridge(ACTIVITY_ANSWER);
457
+ const counting = countingMetrics();
458
+ const countingPaint = { fg: (_role, value) => value, bg: (_role, value) => `\x1b[48;5;240m${value}\x1b[49m` };
459
+ install({ seams: { counting: counting.metrics, paint: countingPaint } });
460
+ const component = promptComponent();
461
+ component.render(60);
462
+ const first = { ...counting.counts };
463
+ assert.ok(first.wrapTextWithAnsi > 0, 'the first frame measures the body');
464
+ component.render(60);
465
+ assert.deepEqual(counting.counts, first, 'a steady frame costs no measurement at all');
466
+ component.render(62);
467
+ assert.ok(counting.counts.wrapTextWithAnsi > first.wrapTextWithAnsi, 'a new width is drawn');
468
+ const beforeStyle = counting.counts.wrapTextWithAnsi;
469
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.FLOAT;
470
+ const rows = component.render(62);
471
+ assert.ok(counting.counts.wrapTextWithAnsi > beforeStyle, 'a style flip is drawn again, never served from the memo');
472
+ assert.match(unpaint(rows[0]), /^\s*▎/u);
473
+ });
474
+
475
+ test('the card carries Pi\'s prompt-zone markers on its own first and last row, exactly once', () => {
476
+ const bridge = publishBridge(ACTIVITY_ANSWER);
477
+ install();
478
+ const component = promptComponent();
479
+ const rows = component.render(60);
480
+ assert.ok(rows[0].startsWith(OSC133_ZONE_START), 'the prompt zone starts where the card starts');
481
+ // Pi's ORDER, byte for byte: the zone-end marker and then the final one, PREFIXED on the last
482
+ // row (`OSC133_ZONE_END + OSC133_ZONE_FINAL + last`), never appended after it.
483
+ assert.ok(rows.at(-1).startsWith(OSC133_ZONE_END + OSC133_ZONE_FINAL), 'end then final, before the last row');
484
+ assert.equal(rows.at(-1).endsWith(OSC133_ZONE_CLOSE), false, 'the close markers are not appended after the row');
485
+ const joined = rows.join('\n');
486
+ assert.equal(joined.split(OSC133_ZONE_START).length - 1, 1, 'one start marker, never two');
487
+ assert.equal(joined.split(OSC133_ZONE_CLOSE).length - 1, 1, 'one end marker, never two');
488
+ for (const row of rows.slice(1, -1)) {
489
+ assert.equal(row.includes(OSC133_ZONE_START) || row.includes(OSC133_ZONE_CLOSE), false, 'no body row carries one');
490
+ }
491
+ assert.equal(chars(rows[0]).length, 60, 'the marker is zero width: the frame still fits exactly');
492
+ // A repaint against the same markers adds no second copy.
493
+ const again = component.render(60);
494
+ assert.equal(again[0].split(OSC133_ZONE_START).length - 1, 1, 'a repaint writes the marker once');
495
+ // The native path is the host's own output, marker for marker, never a card row.
496
+ bridge.answer = { kind: 'native' };
497
+ const native = component.render(60);
498
+ assert.deepEqual(native, NATIVE_RENDER.call(component, 60), 'byte for byte, markers included');
499
+ assert.ok(native[0].startsWith(OSC133_ZONE_START) && native.at(-1).startsWith(OSC133_ZONE_CLOSE));
500
+ assert.equal(native.length, 2, 'the host\'s two rows, with no frame around them');
501
+ });
502
+
503
+ // ---- the rows the terminal pays for ----
504
+
505
+ test('the card pays for the frame only: the clone adds no vertical padding row', () => {
506
+ // The FRAME is the spacing. `lib/file-card-markdown.js` builds its document body with
507
+ // `new Renderer(source, 0, 0, …)` and `lib/message-card.js` hands the substrate plain rows, so
508
+ // no card body carries Markdown's own vertical padding: a prompt of N lines is N body rows,
509
+ // and a blank row the clone put there is a row the terminal pays for with nothing in it.
510
+ publishBridge(ACTIVITY_ANSWER);
511
+ install({ seams: { paint: bandTheme } });
512
+ // The frame's own rows: neon is the heading and the closing rule; float adds the two padding
513
+ // rows of its band above the heading and between the heading and the body.
514
+ for (const [style, frame] of [[CARD_STYLE.NEON, 2], [CARD_STYLE.FLOAT, 4]]) {
515
+ globalThis[CARD_STYLE_SLOT] = style;
516
+ for (const [lines, text] of [[1, 'one line'], [2, 'one line\ntwo lines']]) {
517
+ const rows = promptComponent(text).render(60).map(unpaint);
518
+ for (const row of rows) assert.equal(chars(row).length, 60, `${style}: "${row}" is 60 wide`);
519
+ assert.equal(rows.length, frame + lines, `${style}: ${lines} line(s) are exactly the frame's ${frame} rows plus ${lines} body rows`);
520
+ // And the body is exactly those lines, in order: no blank row the clone put there.
521
+ const body = rows.filter((row) => row.includes('line'));
522
+ assert.equal(body.length, lines, `${style}: ${lines} painted line(s)`);
523
+ for (let index = 1; index < body.length; index += 1) {
524
+ assert.ok(body[index].indexOf('line') > 0, `${style}: body line ${index + 1} is drawn`);
525
+ }
526
+ }
527
+ }
528
+ });
529
+
530
+ // ---- the memo: a style at the same inner width still recomposes ----
531
+
532
+ test('float at the width whose inner equals a neon draw recomposes, with no outline inside the band', () => {
533
+ // Neon at 60 composes at inner 60; float at 62 composes at inner 60 too (it gives two columns
534
+ // to its margins). The chrome is decided by the requested width and the style, not by the
535
+ // inner width alone, so the memo may not serve the neon parts to the float draw.
536
+ publishBridge(ACTIVITY_ANSWER);
537
+ install({ seams: { paint: bandTheme } });
538
+ const component = promptComponent();
539
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
540
+ const neon = component.render(60);
541
+ assert.ok(neon.some((row) => unpaint(row).includes('╭')), 'the neon card drew the rounded frame');
542
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.FLOAT;
543
+ const float = component.render(62);
544
+ // A fresh component has no memo at all: that is exactly what the same instance must match.
545
+ const fresh = promptComponent().render(62);
546
+ assert.deepEqual(float, fresh, 'float at 62 is drawn, not served the neon parts');
547
+ for (const row of float) {
548
+ assert.doesNotMatch(unpaint(row), /[╭╮╰╯]/u, `no rounded glyph inside the float band: ${unpaint(row)}`);
549
+ }
550
+ assert.match(unpaint(float[0]), /^\s*▎/u, 'the float band still opens with its rail');
551
+ assert.equal(chars(float[0]).length, 62, 'and it is still exactly 62 columns wide');
552
+ });
553
+
554
+ // ---- D4: the body follows the live theme, not the one it was cloned under ----
555
+
556
+ test('a theme switch repaints a mounted prompt body, never the theme it was cloned under', () => {
557
+ // Pi's MarkdownTheme is captured when the child is built, so a clone that outlives a theme
558
+ // switch keeps painting the old colours while a freshly built prompt is already new. The
559
+ // clone memo is therefore keyed on the theme used for THIS paint and rebuilds the clone when
560
+ // it differs (the card's paint is live: the theme instance behind Pi's slot changes).
561
+ publishBridge(ACTIVITY_ANSWER);
562
+ const CODE_A = MARKDOWN_CODE;
563
+ const CODE_B = '94';
564
+ const themeA = { fg: (_role, text) => text, bg: (_role, text) => `\x1b[48;5;236m${text}\x1b[49m` };
565
+ const themeB = { fg: (_role, text) => text, bg: (_role, text) => `\x1b[48;5;237m${text}\x1b[49m` };
566
+ let live = themeA;
567
+ install({ seams: { theme: () => live } });
568
+ const mounted = promptComponent();
569
+ const first = mounted.render(60);
570
+ assert.ok(first.some((row) => cells(row).some((cell) => cell.code === CODE_A)), 'the first paint is theme A\'s body');
571
+ // The host switches its theme: a fresh prompt is built under B, and the mounted one must follow.
572
+ StubMarkdown.code = CODE_B;
573
+ live = themeB;
574
+ const second = mounted.render(60);
575
+ const fresh = promptComponent().render(60);
576
+ assert.deepEqual(second, fresh, 'the mounted prompt paints exactly like one built under the new theme');
577
+ for (const row of second) {
578
+ assert.equal(cells(row).some((cell) => cell.code === CODE_A), false, `no cell keeps the old theme: ${unpaint(row)}`);
579
+ }
580
+ assert.ok(second.some((row) => cells(row).some((cell) => cell.code === CODE_B)), 'the new theme paints the body');
581
+ });
582
+
583
+ // ---- D5: a deferred install may not patch a class after its session ended ----
584
+
585
+ /**
586
+ * Load THIS extension (the same stubbing `tools/fixtures/load-extension.js` does) and hand back
587
+ * its own module namespace, because the deferred install's seam lives there: a test must be able
588
+ * to make Pi's package resolve LATE, after the session ended. The bridge is published before the
589
+ * factory runs, exactly as the fixture does, so the activity design registers.
590
+ */
591
+ async function loadExtensionModule(loader, events = {}, options = {}) {
592
+ process.env.GENTLE_WORKTREE_LIB_DIR = fixture.LIB_DIR;
593
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'odd-worktree-upc-'));
594
+ try {
595
+ const copy = path.join(dir, 'odd-worktree-tools.mjs');
596
+ fs.writeFileSync(copy, fixture.stubbedSource());
597
+ const namespace = await import(pathToFileURL(copy).href);
598
+ if (typeof namespace.setUserPromptCardHostLoader !== 'function') {
599
+ throw new Error('the extension exposes no seam for the deferred prompt-card install');
600
+ }
601
+ const hooks = [];
602
+ const host = {
603
+ registerCommand() {},
604
+ registerTool() {},
605
+ registerMessageRenderer() {},
606
+ registerEntryRenderer() {},
607
+ appendEntry() {},
608
+ on: (event, handler) => hooks.push([event, handler]),
609
+ // The host's event bus, when a test needs the bridge's ready announcement (`pi.events`).
610
+ events,
611
+ };
612
+ // A host SHAPE a test needs: an `on` that accepts some events and refuses others, or none at
613
+ // all (`null`), which is how a host that cannot own a teardown is modelled.
614
+ if (options.on !== undefined) {
615
+ if (options.on === null) delete host.on;
616
+ else host.on = options.on;
617
+ }
618
+ namespace.setUserPromptCardHostLoader(loader);
619
+ namespace.default(host);
620
+ return { namespace, hooks };
621
+ } finally {
622
+ fs.rmSync(dir, { recursive: true, force: true });
623
+ }
624
+ }
625
+
626
+ /** Every hook the extension registered for one event, emitted the way the host would. */
627
+ const extensionSession = (hooks) => (event) => Promise.all(hooks.filter(([name]) => name === event).map(([, handler]) => handler({}, {})));
628
+
629
+ const drain = () => new Promise((resolve) => setImmediate(resolve));
630
+
631
+ test('an install whose import resolves after shutdown patches nothing', async () => {
632
+ // `installUserPromptCard()` awaits a dynamic import; a session that ends inside that window
633
+ // must not be patched afterwards, or the prototype stays wrapped into the next session.
634
+ const bridge = fixture.defaultBridge();
635
+ const previousBridge = globalThis[BRIDGE_API_SLOT];
636
+ globalThis[BRIDGE_API_SLOT] = bridge.api;
637
+ class LateHost {
638
+ render(width) {
639
+ return [`native ${width}`];
640
+ }
641
+ }
642
+ const native = LateHost.prototype.render;
643
+ let release;
644
+ const gate = new Promise((resolve) => {
645
+ release = () => resolve({ UserMessageComponent: LateHost });
646
+ });
647
+ try {
648
+ const { hooks } = await loadExtensionModule(() => gate);
649
+ const emit = extensionSession(hooks);
650
+ const shutdowns = hooks.filter(([event]) => event === 'session_shutdown').map(([, handler]) => handler);
651
+ assert.ok(shutdowns.length > 0, 'the session boundary is registered');
652
+ await emit('session_start');
653
+ await drain();
654
+ assert.equal(LateHost.prototype.render, native, 'nothing is patched while the import is pending');
655
+ // The session ends BEFORE Pi's package resolves.
656
+ for (const handler of shutdowns) await handler({}, {});
657
+ release();
658
+ await new Promise((resolve) => setTimeout(resolve, 20));
659
+ assert.equal(LateHost.prototype.render, native, 'a late install patches nothing after shutdown');
660
+ } finally {
661
+ if (previousBridge === undefined) delete globalThis[BRIDGE_API_SLOT];
662
+ else globalThis[BRIDGE_API_SLOT] = previousBridge;
663
+ }
664
+ });
665
+
666
+ // ---- S7: the install lifecycle survives the epoch it belongs to ----
667
+
668
+ test('S7: a pending install from a closed session cannot suppress the next install', async () => {
669
+ globalThis[BRIDGE_API_SLOT] = fixture.defaultBridge().api;
670
+ class Host {
671
+ render() {
672
+ return ['native'];
673
+ }
674
+ }
675
+ const native = Host.prototype.render;
676
+ let release;
677
+ const pending = new Promise((resolve) => {
678
+ release = resolve;
679
+ });
680
+ let calls = 0;
681
+ const { hooks } = await loadExtensionModule(() => (++calls === 1 ? pending : { UserMessageComponent: Host }));
682
+ const emit = extensionSession(hooks);
683
+ try {
684
+ await emit('session_start');
685
+ await drain();
686
+ assert.equal(calls, 1, 'the session start armed one import');
687
+ await emit('session_shutdown');
688
+ await emit('session_start');
689
+ release({ UserMessageComponent: Host });
690
+ await drain();
691
+ assert.equal(calls, 2, 'the new session drives its OWN install, not the closed one\'s');
692
+ assert.notEqual(Host.prototype.render, native, 'the new session is patched');
693
+ } finally {
694
+ await emit('session_shutdown');
695
+ }
696
+ });
697
+
698
+ test('S7: bridge readiness after shutdown cannot arm a host import', async () => {
699
+ delete globalThis[BRIDGE_API_SLOT];
700
+ class Host {
701
+ render() {
702
+ return ['native'];
703
+ }
704
+ }
705
+ const native = Host.prototype.render;
706
+ let release;
707
+ const pending = new Promise((resolve) => {
708
+ release = resolve;
709
+ });
710
+ const listeners = new Map();
711
+ const { hooks } = await loadExtensionModule(() => pending, {
712
+ on: (event, handler) => listeners.set(event, handler),
713
+ });
714
+ for (const [event, handler] of [...hooks]) {
715
+ if (event === 'session_shutdown') await handler({}, {});
716
+ }
717
+ globalThis[BRIDGE_API_SLOT] = fixture.defaultBridge().api;
718
+ listeners.get('gentle-shell-bridge:ready')?.();
719
+ release({ UserMessageComponent: Host });
720
+ await drain();
721
+ assert.equal(Host.prototype.render, native);
722
+ });
723
+
724
+ test('S7: factory load does not arm a host import before session_start', async () => {
725
+ // Pi loads the factory before any session exists, and caches it across sessions. A load may
726
+ // neither arm the host import nor patch the class until a `session_start` opens the session
727
+ // that owns the card.
728
+ const previousBridge = globalThis[BRIDGE_API_SLOT];
729
+ globalThis[BRIDGE_API_SLOT] = fixture.defaultBridge().api;
730
+ class Host {
731
+ render() {
732
+ return ['native'];
733
+ }
734
+ }
735
+ const native = Host.prototype.render;
736
+ let calls = 0;
737
+ const { hooks } = await loadExtensionModule(() => {
738
+ calls += 1;
739
+ return { UserMessageComponent: Host };
740
+ });
741
+ const emit = extensionSession(hooks);
742
+ try {
743
+ // A macrotask: every microtask of the load has run by now.
744
+ await drain();
745
+ assert.equal(calls, 0, 'no loader call before a session exists');
746
+ assert.equal(Host.prototype.render, native, 'and an untouched prototype');
747
+ await emit('session_start');
748
+ await drain();
749
+ assert.equal(calls, 1, 'the first session drives exactly one install');
750
+ assert.notEqual(Host.prototype.render, native, 'and the class is patched then');
751
+ await emit('session_shutdown');
752
+ assert.equal(Host.prototype.render, native, 'and its shutdown restores it');
753
+ } finally {
754
+ await emit('session_shutdown');
755
+ if (previousBridge === undefined) delete globalThis[BRIDGE_API_SLOT];
756
+ else globalThis[BRIDGE_API_SLOT] = previousBridge;
757
+ }
758
+ });
759
+
760
+ test('S7: silent publication on a host without a bus acquires a shutdown owner', async () => {
761
+ // The gate observer is a WAKE-UP path, not a session: a bridge published silently wakes the
762
+ // surface from a `session_start`, and that same load must then own the shutdown that unwraps
763
+ // it. With no event bus the observer is the only way in.
764
+ const previousBridge = globalThis[BRIDGE_API_SLOT];
765
+ delete globalThis[BRIDGE_API_SLOT];
766
+ class Host {
767
+ render() {
768
+ return ['native'];
769
+ }
770
+ }
771
+ const native = Host.prototype.render;
772
+ const { hooks } = await loadExtensionModule(() => ({ UserMessageComponent: Host }));
773
+ const emit = extensionSession(hooks);
774
+ try {
775
+ assert.deepEqual(hooks.map(([event]) => event), ['session_start'], 'a gate-closed load keeps its ONE observer');
776
+ // A SILENT publication: nothing announces it, so `session_start` is what wakes the surface.
777
+ globalThis[BRIDGE_API_SLOT] = fixture.defaultBridge().api;
778
+ await emit('session_start');
779
+ await drain();
780
+ assert.notEqual(Host.prototype.render, native, 'the waking session draws the card');
781
+ await emit('session_shutdown');
782
+ assert.equal(Host.prototype.render, native, 'and it owns the shutdown that unwraps it');
783
+ } finally {
784
+ await emit('session_shutdown');
785
+ if (previousBridge === undefined) delete globalThis[BRIDGE_API_SLOT];
786
+ else globalThis[BRIDGE_API_SLOT] = previousBridge;
787
+ }
788
+ });
789
+
790
+ // ---- S7: owning the teardown is a precondition of installing ----
791
+
792
+ test('S7: a host that refuses the shutdown hook owns no patch', async () => {
793
+ // Owning a teardown is a PRECONDITION of installing (fail closed). A host that accepts
794
+ // `session_start` and refuses `session_shutdown` would otherwise leave the card installed with
795
+ // nobody to unwrap it, so it gets no patch at all: its prompt stays Pi's own.
796
+ const previousBridge = globalThis[BRIDGE_API_SLOT];
797
+ globalThis[BRIDGE_API_SLOT] = fixture.defaultBridge().api;
798
+ class Host {
799
+ render() {
800
+ return ['native'];
801
+ }
802
+ }
803
+ const native = Host.prototype.render;
804
+ let calls = 0;
805
+ const accepted = [];
806
+ try {
807
+ await loadExtensionModule(
808
+ () => {
809
+ calls += 1;
810
+ return { UserMessageComponent: Host };
811
+ },
812
+ {},
813
+ {
814
+ on: (event, handler) => {
815
+ // The start hook is accepted; the shutdown hook is refused.
816
+ if (event === 'session_shutdown') throw new Error('this host refuses the shutdown hook');
817
+ accepted.push([event, handler]);
818
+ },
819
+ },
820
+ );
821
+ await drain();
822
+ assert.equal(calls, 0, 'the loader is never called: no teardown, no patch');
823
+ assert.equal(Host.prototype.render, native, 'and the prototype is never patched');
824
+ // A session that starts anyway cannot open a session this load does not own.
825
+ for (const [event, handler] of accepted) {
826
+ if (event === 'session_start') await handler({}, {});
827
+ }
828
+ await drain();
829
+ assert.equal(calls, 0, 'no session start arms an unowned install');
830
+ assert.equal(Host.prototype.render, native, 'and the class stays Pi\'s own');
831
+ } finally {
832
+ if (previousBridge === undefined) delete globalThis[BRIDGE_API_SLOT];
833
+ else globalThis[BRIDGE_API_SLOT] = previousBridge;
834
+ }
835
+ });
836
+
837
+ test('S7: a host with no session hooks owns no patch either', async () => {
838
+ const previousBridge = globalThis[BRIDGE_API_SLOT];
839
+ globalThis[BRIDGE_API_SLOT] = fixture.defaultBridge().api;
840
+ class Host {
841
+ render() {
842
+ return ['native'];
843
+ }
844
+ }
845
+ const native = Host.prototype.render;
846
+ let calls = 0;
847
+ try {
848
+ await loadExtensionModule(
849
+ () => {
850
+ calls += 1;
851
+ return { UserMessageComponent: Host };
852
+ },
853
+ {},
854
+ { on: null },
855
+ );
856
+ await drain();
857
+ assert.equal(calls, 0, 'a host with no `on` owns no teardown, so the loader is never called');
858
+ assert.equal(Host.prototype.render, native, 'and the prototype stays untouched');
859
+ } finally {
860
+ if (previousBridge === undefined) delete globalThis[BRIDGE_API_SLOT];
861
+ else globalThis[BRIDGE_API_SLOT] = previousBridge;
862
+ }
863
+ });
864
+
865
+ // ---- S5/S6: one wrapper per process, torn down on demand ----
866
+
867
+ test('installing twice wraps once, and uninstall restores the original render byte for byte', () => {
868
+ publishBridge(ACTIVITY_ANSWER);
869
+ const first = install();
870
+ assert.equal(first.installed, true);
871
+ const wrapped = UserMessageComponent.prototype.render;
872
+ assert.notEqual(wrapped, NATIVE_RENDER);
873
+ const second = install();
874
+ assert.equal(second.installed, true);
875
+ assert.equal(UserMessageComponent.prototype.render, wrapped, 'a second install adds no second layer');
876
+ const component = promptComponent();
877
+ assert.match(unpaint(component.render(60)[0]), /^╭─ ✿ You /u, 'the card is still drawn through one wrapper');
878
+ // The wrapper always calls the MOST RECENTLY installed logic, which is what a `/reload`
879
+ // relies on: a second install with its own seams paints with those seams, not with the first.
880
+ install({ seams: { paint: taggedTheme } });
881
+ assert.ok(component.render(60)[0].includes('<accent>✿ You</accent>'), 'the newest logic paints');
882
+ uninstallUserPromptCard();
883
+ assert.equal(UserMessageComponent.prototype.render, NATIVE_RENDER, 'the original function is back');
884
+ const fresh = promptComponent();
885
+ assert.deepEqual(fresh.render(60), nativeRows(fresh, 60));
886
+ });
887
+
888
+ test('a class without render, an absent class and a component with no Markdown install and answer native', () => {
889
+ publishBridge(ACTIVITY_ANSWER);
890
+ const refused = installUserPromptCard({});
891
+ assert.equal(refused.installed, false);
892
+ assert.equal(typeof refused.uninstall, 'function', 'a refused install still answers an inert uninstall');
893
+ assert.equal(installUserPromptCard({ component: class Empty {} }).installed, false);
894
+ assert.equal(installUserPromptCard({ component: 42 }).installed, false);
895
+ assert.equal(UserMessageComponent.prototype.render, NATIVE_RENDER, 'nothing was wrapped for a class that cannot draw');
896
+ const shapes = [
897
+ ['no children at all', () => new UserMessageComponent(PROMPT, { children: null })],
898
+ ['an empty child list', () => new UserMessageComponent(PROMPT, { children: [] })],
899
+ ['a child that is not an object', () => new UserMessageComponent(PROMPT, { children: ['markdown'] })],
900
+ ['a non-numeric paddingX', () => new UserMessageComponent(PROMPT, { paddingX: '1' })],
901
+ ['no Markdown theme', () => new UserMessageComponent(PROMPT, { markdownTheme: null })],
902
+ ];
903
+ install();
904
+ for (const [name, build] of shapes) {
905
+ const component = build();
906
+ assert.deepEqual(component.render(60), nativeRows(component, 60), name);
907
+ }
908
+ // A child whose constructor is not a function, and one that is no Markdown at all.
909
+ const constructorless = promptComponent();
910
+ constructorless.children[0].constructor = undefined;
911
+ assert.deepEqual(constructorless.render(60), nativeRows(constructorless, 60), 'constructor not a function');
912
+ const plain = promptComponent();
913
+ plain.children[0] = { text: PROMPT, paddingX: 1, theme: {} };
914
+ assert.deepEqual(plain.render(60), nativeRows(plain, 60), 'a plain object is no Markdown');
915
+ });
916
+
917
+ test('a body the card cannot read answers native: no row, an answer that is not rows, a renderer that throws', () => {
918
+ publishBridge(ACTIVITY_ANSWER);
919
+ install();
920
+ for (const [name, text] of [['a body that draws no row', 'EMPTY_BODY'], ['an answer that is not rows', 'NOT_ROWS'], ['a renderer that throws', 'THROW']]) {
921
+ const component = promptComponent(text);
922
+ assert.deepEqual(component.render(60), nativeRows(component, 60), name);
923
+ }
924
+ });
925
+
926
+ test('a metrics or theme seam that throws, or answers nothing usable, answers native too', () => {
927
+ publishBridge(ACTIVITY_ANSWER);
928
+ install({
929
+ seams: {
930
+ metrics: () => { throw new Error('no tui package'); },
931
+ theme: () => { throw new Error('no theme'); },
932
+ },
933
+ });
934
+ const component = promptComponent();
935
+ assert.deepEqual(component.render(60), nativeRows(component, 60), 'both seams throw');
936
+ uninstallUserPromptCard();
937
+ install({ seams: { metrics: () => ({}), theme: () => ({}) } });
938
+ assert.deepEqual(promptComponent().render(60), nativeRows(promptComponent(), 60), 'a metrics object that cannot measure');
939
+ uninstallUserPromptCard();
940
+ install({ seams: { metrics: () => undefined, theme: () => undefined } });
941
+ assert.deepEqual(promptComponent().render(60), nativeRows(promptComponent(), 60), 'seams that answer nothing');
942
+ uninstallUserPromptCard();
943
+ const hostile = { fg: () => { throw new Error('boom'); }, bg: () => { throw new Error('boom'); } };
944
+ install({ seams: { paint: hostile } });
945
+ assert.deepEqual(promptComponent().render(60), nativeRows(promptComponent(), 60), 'a theme that throws');
946
+ });
947
+
948
+ test('an empty prompt draws no card: the host\'s own nothing comes back', () => {
949
+ publishBridge(ACTIVITY_ANSWER);
950
+ install();
951
+ const component = new UserMessageComponent(PROMPT, { empty: true });
952
+ assert.deepEqual(component.render(60), []);
953
+ });
954
+
955
+ test('the heading is this package\'s card: the accent name, no subtitle and no time', () => {
956
+ publishBridge(ACTIVITY_ANSWER);
957
+ install({ seams: { paint: taggedTheme } });
958
+ const component = promptComponent();
959
+ const head = component.render(60)[0];
960
+ assert.ok(head.includes('<accent>✿ You</accent>'), 'the mark and the name wear the title role together');
961
+ assert.equal(unpaint(head).includes('·'), false, 'no subtitle separator');
962
+ assert.doesNotMatch(unpaint(head), /\d{1,2}:\d{2}|ago/u, 'no timestamp: gentle-timestamps owns the clock');
963
+ });