pi-odd-worktree 3.9.0 → 3.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/jobs-card.js CHANGED
@@ -36,7 +36,17 @@ const {
36
36
  floatRows,
37
37
  markCardResult,
38
38
  } = require('./shell-card.js');
39
- const { PREVIEW_ROWS, cardTone, component, expandHint, fileResultRows, optionFlag, resultText, themeFor } = require('./file-card.js');
39
+ const {
40
+ PREVIEW_ROWS,
41
+ cardTone,
42
+ component,
43
+ expandHint,
44
+ fileResultRows,
45
+ hostFallbackRows,
46
+ optionFlag,
47
+ resultText,
48
+ themeFor,
49
+ } = require('./file-card.js');
40
50
  // The one reader of text as a card draws it: no terminal sequences, however the model wrote it.
41
51
  const { cardText } = require('./codegraph-card-preview.js');
42
52
 
@@ -144,10 +154,31 @@ function jobCallRows(tool, args, context, paint, metrics, width) {
144
154
  }
145
155
 
146
156
  /**
147
- * The call slot. The seams are read on every frame, so a measurement seam that arrives late
148
- * is used by the next paint rather than never.
157
+ * The rows Pi's own drawing states for one half of this tool while the `Card activity` line
158
+ * says anything but `activity`: the host's fallback text inside the host's own box (or bare,
159
+ * for a tool that frames itself), reproduced by `lib/file-card.js` because Pi builds them
160
+ * inside its own component and publishes neither.
161
+ */
162
+ function hostRows(slot, tool, seams, shell, context, paint, width, input) {
163
+ return hostFallbackRows({
164
+ slot,
165
+ tool,
166
+ ...input,
167
+ width,
168
+ context,
169
+ paint,
170
+ seams,
171
+ shell,
172
+ });
173
+ }
174
+
175
+ /**
176
+ * The call slot. The switch, the seams and the measurement are all read INSIDE the
177
+ * component's build, which the host runs on every frame: a card already on screen repaints
178
+ * when the bridge's `Card activity` line changes, and while it says anything but `activity`
179
+ * the component draws what Pi draws for a tool with no renderer at all.
149
180
  */
150
- function jobCallSlot(tool, seams) {
181
+ function jobCallSlot(tool, seams, shell) {
151
182
  return (args, theme, context) => {
152
183
  try {
153
184
  const ctx = asObject(context);
@@ -155,7 +186,10 @@ function jobCallSlot(tool, seams) {
155
186
  const paint = themeFor(theme, seams.theme);
156
187
  return component((width) => {
157
188
  const metrics = seams.metrics();
158
- return metrics === undefined ? [] : jobCallRows(tool, callArgs, ctx, paint, metrics, width);
189
+ if (metrics !== undefined && seams.enabled(tool) === true) {
190
+ return jobCallRows(tool, callArgs, ctx, paint, metrics, width);
191
+ }
192
+ return hostRows('call', tool, seams, shell, ctx, paint, width, { args: callArgs });
159
193
  });
160
194
  } catch {
161
195
  return { render: () => [], invalidate() {} };
@@ -165,9 +199,10 @@ function jobCallSlot(tool, seams) {
165
199
 
166
200
  /**
167
201
  * The result slot: the job's own answer — a bounded preview collapsed, everything expanded —
168
- * under the call, closing the frame the call left open.
202
+ * under the call, closing the frame the call left open. The switch is read in here too, for
203
+ * the reason the call slot states, and off it draws the host's own result fallback.
169
204
  */
170
- function jobResultSlot(tool, seams) {
205
+ function jobResultSlot(tool, seams, shell) {
171
206
  return (result, options, theme, context) => {
172
207
  try {
173
208
  const ctx = asObject(context);
@@ -175,14 +210,22 @@ function jobResultSlot(tool, seams) {
175
210
  const paint = themeFor(theme, seams.theme);
176
211
  const failed = asObject(result).isError === true || optionFlag(options, ctx, 'isError');
177
212
  const partial = optionFlag(options, ctx, 'isPartial');
213
+ // The state the host's own box is painted in: still streaming, then failed, then success.
214
+ const boxContext = { ...ctx, isPartial: partial, isError: failed };
178
215
  const identity = IDENTITY[tool] ?? IDENTITY.bash_background;
216
+ // One frame, marked when the host BUILDS this half and not while it paints it: the host
217
+ // builds the result component in `updateDisplay()` and only then renders the pass, so a
218
+ // mark made while painting would arrive after the call above already drew — one row too
219
+ // many on the first paint of a partial result.
220
+ markCardResult(ctx.state);
179
221
  return component((width) => {
180
222
  const metrics = seams.metrics();
181
- if (metrics === undefined) return [];
223
+ if (metrics === undefined || seams.enabled(tool) !== true) {
224
+ // `expanded` is the host's own, so a fallback result follows the card's expansion.
225
+ return hostRows('result', tool, seams, shell, { ...boxContext, expanded: optionFlag(options, ctx, 'expanded') }, paint, width, { result });
226
+ }
182
227
  const expanded = optionFlag(options, ctx, 'expanded');
183
228
  const tone = cardTone(failed, partial);
184
- // One frame: from here on the call above is a heading and this card closes it.
185
- markCardResult(ctx.state);
186
229
  return floatRows(tone, paint, width, (inner) => {
187
230
  const rows = fileResultRows({
188
231
  text: resultText(result),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-odd-worktree",
3
- "version": "3.9.0",
3
+ "version": "3.9.1",
4
4
  "description": "Pi package for odd-worktree: the Git worktree tools a Pi session uses (create and list the checkouts the agent works in), the /warp worktree panel, the /odd ODD viewer, and the /issues GitHub issue reader. Needs only Pi and git: no companion app, no extra service.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -1617,9 +1617,9 @@ test('the audit\'s real PR command names the publishing activity', () => {
1617
1617
 
1618
1618
  The four tools are declared on the \`tags\` line so the bridge can answer for them; the activity design itself returns their rows exactly as drawn.
1619
1619
 
1620
- ## Limitation
1620
+ ## Repaint
1621
1621
 
1622
- The gate is read when a job card is built, not on every paint: these tools have no host renderer to forward to, so a switch made mid-session reaches the next job card.
1622
+ The gate is read on every paint, inside the component the host already mounted, so flipping \`Card activity\` between \`default\` and \`activity\` repaints the job cards already on screen. Off, the card draws the host's own fallback row and box, reproduced, because these tools have no host renderer to hand the row back to.
1623
1623
 
1624
1624
  ## Tests
1625
1625
 
@@ -100,6 +100,16 @@ const plainTheme = {
100
100
  },
101
101
  };
102
102
 
103
+ // The host's own palette, as far as a test can see it: every role is named and bold is its
104
+ // own tag, so the rows this package hands back can be compared with the host's drawing
105
+ // byte for byte.
106
+ const hostTheme = {
107
+ fg: (role, value) => `<${role}>${value}</${role}>`,
108
+ bg: (role, value) => `<${role}>${value}</${role}>`,
109
+ bold: (value) => `<bold>${value}</bold>`,
110
+ };
111
+ const hostRow = (role, text, width) => `<${role}>${text.padEnd(width)}</${role}>`;
112
+
103
113
  /** A theme that can also paint the float background, so the text stays readable. */
104
114
  function paintTheme() {
105
115
  const roles = { fg: [], bg: [] };
@@ -210,6 +220,195 @@ after(() => {
210
220
  delete globalThis[BRIDGE_API_SLOT];
211
221
  });
212
222
 
223
+ /** A host that draws CodeGraph rows itself: the chain's renderers, captured when the card was built. */
224
+ const HOST_CODEGRAPH = {
225
+ renderShell: 'self',
226
+ renderCall: () => ({ render: (width) => [`host call ${width}`.padEnd(width, ' ')], invalidate() {} }),
227
+ renderResult: () => ({ render: (width) => [`host result ${width}`.padEnd(width, ' ')], invalidate() {} }),
228
+ };
229
+
230
+ // ---- the switch, read per paint ----
231
+ //
232
+ // Pi resolves a tool's renderers ONCE, when it mounts the card
233
+ // (`interactive-mode.js` hands the resolved definition to `ToolExecutionComponent`), and
234
+ // never asks again. The bridge's `Card activity` line is therefore read INSIDE the
235
+ // component's build, which the host does run on every frame: the cases below mount one
236
+ // card, flip the line, and repaint that same component.
237
+
238
+ test('the line is read on every paint: a mounted card hands the row back to the chain and takes it again', () => {
239
+ publishBridge(ACTIVITY_ON);
240
+ const resolver = cardFor({ cwd: '/work/repo' });
241
+ const slot = renderersFor(resolver, CODEGRAPH_TOOL, HOST_CODEGRAPH);
242
+ const args = { operation: 'explore', query: 'auth login' };
243
+ const context = { args, isPartial: false };
244
+ // ONE card, mounted: the components the host built before any of this changed.
245
+ const call = slot.renderCall(args, hostTheme, context);
246
+ const result = slot.renderResult(textResult('found it'), { isPartial: false }, hostTheme, context);
247
+ const on = { call: call.render(60), result: result.render(60) };
248
+ assert.ok(on.call.length > 0, 'the card is drawn while the line says activity');
249
+ assert.ok(on.result.length > 0, 'and its result half too');
250
+ // The line is turned off, and the SAME mounted components are repainted.
251
+ publishBridge({ kind: 'native' });
252
+ assert.deepEqual(call.render(60), [`host call 60`.padEnd(60, ' ')], 'off, the chain\'s own renderer draws the row it captured at build time');
253
+ assert.deepEqual(result.render(60), [`host result 60`.padEnd(60, ' ')], 'the result half too');
254
+ // And back on, from the same two components.
255
+ publishBridge(ACTIVITY_ON);
256
+ assert.deepEqual(call.render(60), on.call, 'flipped back on, the card is drawn again, unchanged');
257
+ assert.deepEqual(result.render(60), on.result, 'the result half too');
258
+ });
259
+
260
+ test('the line is read on every paint for all three surfaces and a bash call that runs CodeGraph', () => {
261
+ // The mounted-repaint contract (S1): ONE component per surface, mounted while the line says
262
+ // `activity`, repainted after the line is turned off and after it is turned back on.
263
+ const surfaces = [
264
+ [CODEGRAPH_TOOL, { operation: 'explore', query: 'auth login' }, 'the native tool'],
265
+ [CODEGRAPH_MCP_TOOL, { query: 'auth login' }, 'the MCP tool, bare name'],
266
+ [MCP_PREFIXED_TOOL, { query: 'auth login' }, 'the MCP tool, prefixed name'],
267
+ ['bash', { command: 'codegraph explore -- auth login' }, 'a bash call that runs CodeGraph'],
268
+ ];
269
+ const flips = [];
270
+ for (const [tool, args, label] of surfaces) {
271
+ publishBridge(ACTIVITY_ON);
272
+ const resolver = cardFor({ cwd: '/work/repo' });
273
+ const slot = renderersFor(resolver, tool, HOST_CODEGRAPH);
274
+ const context = { args, isPartial: false };
275
+ const call = slot.renderCall(args, hostTheme, context);
276
+ const on = call.render(60);
277
+ assert.ok(on.length > 0 && !on.join('\n').includes('host call'), `${label}: the card is drawn while the line says activity`);
278
+ publishBridge({ kind: 'native' });
279
+ assert.deepEqual(call.render(60), [`host call 60`.padEnd(60, ' ')], `${label}: flipped off, the chain's own rows are drawn`);
280
+ publishBridge(ACTIVITY_ON);
281
+ assert.deepEqual(call.render(60), on, `${label}: flipped back on, the card is drawn again, unchanged`);
282
+ flips.push(label);
283
+ }
284
+ assert.equal(flips.length, 4, 'four surfaces, four mounted repaints, each in both directions');
285
+ publishBridge(ACTIVITY_ON);
286
+ });
287
+
288
+ test('a captured renderer that throws falls back to the host\'s own drawing', () => {
289
+ // Pi catches a renderer that throws and draws `createCallFallback()` in its place
290
+ // (`ToolExecutionComponent.updateDisplay`); the card must do the same rather than lose the row.
291
+ const throwing = {
292
+ renderShell: 'self',
293
+ renderCall() {
294
+ throw new Error('host renderer exploded');
295
+ },
296
+ renderResult() {
297
+ throw new Error('host renderer exploded');
298
+ },
299
+ };
300
+ publishBridge({ kind: 'native' });
301
+ try {
302
+ const resolver = cardFor({ cwd: '/work/repo' });
303
+ const call = renderersFor(resolver, CODEGRAPH_TOOL, throwing).renderCall({ operation: 'status' }, hostTheme, { isPartial: false }).render(120);
304
+ const title = `<toolTitle><bold>${CODEGRAPH_TOOL}</bold></title>`.replace('</title>', '</toolTitle>');
305
+ // The host's own fallback row; Pi prepends its one separator blank for a self-framed tool,
306
+ // which is the baseline's two rows.
307
+ assert.deepEqual(call, [`${title} <muted>operation="status"</muted>`.padEnd(120, ' ')]);
308
+ } finally {
309
+ publishBridge(ACTIVITY_ON);
310
+ }
311
+ });
312
+
313
+ test('ordinary bash keeps the same clickable child while activity is off', () => {
314
+ // The verifier's own dispatch check, kept here so a future wrapper cannot silently swallow a
315
+ // click: with the line off the host mounts the child's component ITSELF, and its mouse handler
316
+ // is the one that runs.
317
+ publishBridge({ kind: 'native' });
318
+ try {
319
+ let clicks = 0;
320
+ const child = {
321
+ render: () => ['ordinary bash'],
322
+ invalidate() {},
323
+ handleMouse() { clicks += 1; return { handled: true }; },
324
+ };
325
+ const chain = { renderShell: 'self', renderCall: () => child };
326
+ const resolved = cardFor({ cwd: '/work/repo' })('bash', () => chain);
327
+ assert.equal(resolved, chain);
328
+ const mounted = resolved.renderCall({ command: 'printf ordinary' }, plainTheme, {});
329
+ assert.equal(mounted, child);
330
+ assert.deepEqual(mounted.handleMouse({ type: 'click', button: 'left' }), { handled: true });
331
+ assert.equal(clicks, 1);
332
+ } finally {
333
+ publishBridge(ACTIVITY_ON);
334
+ }
335
+ });
336
+
337
+ test('with the line off a bash row is handed back untouched, never wrapped', () => {
338
+ // A bash call's own component is what the host mounts, so its rows, its mouse handling and
339
+ // every other behaviour stay exactly as Pi resolved them: off, this card adds no wrapper.
340
+ publishBridge({ kind: 'native' });
341
+ try {
342
+ const chain = {
343
+ renderShell: 'self',
344
+ renderCall: () => ({ render: () => ['the chain drew this'], invalidate() {} }),
345
+ renderResult: () => ({ render: () => ['the chain drew this too'], invalidate() {} }),
346
+ };
347
+ for (const command of ['pnpm test', 'codegraph status .']) {
348
+ assert.equal(cardFor({ cwd: '/work/repo' })('bash', () => chain), chain, command);
349
+ }
350
+ } finally {
351
+ publishBridge(ACTIVITY_ON);
352
+ }
353
+ // While the line says activity the card is the one answering, so a flip can repaint it.
354
+ const chain = { renderShell: 'self', renderCall: () => ({ render: () => [], invalidate() {} }), renderResult: () => ({ render: () => [], invalidate() {} }) };
355
+ assert.equal(cardFor({ cwd: '/work/repo' })('bash', () => chain).renderShell, 'self', 'activity on: the card answers the bash row');
356
+ });
357
+
358
+ test('a PARTIAL result draws the rows every later paint draws, on the FIRST paint', () => {
359
+ // Pi builds the result component when the update arrives (`updateDisplay`) and only then
360
+ // renders the pass. A mark made while painting lands after the call already drew, so the first
361
+ // partial paint carries one row too many (the verifier measured 5/4 neon, 8/7 float). The card
362
+ // marks during construction, like the baseline: the first paint is the one every paint repeats.
363
+ publishBridge(ACTIVITY_ON);
364
+ const resolver = cardFor({ cwd: '/work/repo' });
365
+ const args = { operation: 'explore', query: 'auth login' };
366
+ const text = textResult('found it');
367
+ for (const isPartial of [true, false]) {
368
+ const state = {};
369
+ const context = { args, isPartial, state };
370
+ // One card, built the way the host builds it: the result's component first, then the call's.
371
+ const slot = renderersFor(resolver, CODEGRAPH_TOOL, HOST_CODEGRAPH);
372
+ const result = slot.renderResult(text, { isPartial }, hostTheme, context);
373
+ const call = slot.renderCall(args, hostTheme, context);
374
+ const first = [...call.render(70), ...result.render(70)].map(unpaint);
375
+ const again = [...call.render(70), ...result.render(70)].map(unpaint);
376
+ assert.deepEqual(first, again, `isPartial=${isPartial}: the first paint is the one every later paint draws`);
377
+ const closers = first.filter((row) => row.startsWith('╰')).length;
378
+ assert.equal(closers, isPartial ? 0 : 1, `isPartial=${isPartial}: one frame, closed only by the settled result`);
379
+ assert.equal(call.render(70).map(unpaint).filter((row) => row.startsWith('╰')).length, 0, `isPartial=${isPartial}: the call never closes it`);
380
+ }
381
+ });
382
+
383
+ test('with the line off and no renderer in the chain, the rows are the host\'s own fallback, byte for byte', () => {
384
+ publishBridge({ kind: 'native' });
385
+ try {
386
+ const resolver = cardFor({ cwd: '/work/repo' });
387
+ const args = { query: 'auth login' };
388
+ // The MCP tool's definition declares no shell, so Pi draws its fallback inside its own
389
+ // box: one painted blank row, the padded call, one painted blank row.
390
+ const mcp = renderersFor(resolver, MCP_PREFIXED_TOOL, undefined);
391
+ const boxed = mcp.renderCall(args, hostTheme, { args, isPartial: false, outputPad: 1 }).render(120);
392
+ const title = `<toolTitle><bold>${MCP_PREFIXED_TOOL}</bold></toolTitle>`;
393
+ // The call half opens the box; its closing blank belongs to the result half, which
394
+ // is where the host draws it once the result exists.
395
+ assert.deepEqual(boxed, [
396
+ hostRow('toolSuccessBg', ' '.repeat(120), 120),
397
+ hostRow('toolSuccessBg', ` ${title} <muted>query="auth login"</muted>`, 120),
398
+ ]);
399
+ // The native tool frames itself (`renderShell: 'self'` in its own definition), and Pi
400
+ // draws no box around a tool that does: the fallback rows alone, padded.
401
+ const native = renderersFor(resolver, CODEGRAPH_TOOL, { renderShell: 'self' });
402
+ const bare = native.renderCall({ operation: 'status' }, hostTheme, { isPartial: false, outputPad: 1 }).render(120);
403
+ const nativeTitle = `<toolTitle><bold>${CODEGRAPH_TOOL}</bold></toolTitle>`;
404
+ assert.deepEqual(bare, [`${nativeTitle} <muted>operation="status"</muted>`.padEnd(120, ' ')]);
405
+ // A result that states nothing draws no row at all, exactly as the host's own fallback.
406
+ assert.deepEqual(native.renderResult(textResult(''), { isPartial: false }, hostTheme, { args: { operation: 'status' } }).render(60), []);
407
+ } finally {
408
+ publishBridge(ACTIVITY_ON);
409
+ }
410
+ });
411
+
213
412
  // ---- the resolver under test ----
214
413
 
215
414
  /** No hook at all would be the host's own: every case here registers through the probe. */
@@ -987,23 +1186,37 @@ test('S11: `native`, `not-covered`, `missing`, another design and a throwing rea
987
1186
  undefined,
988
1187
  null,
989
1188
  ];
1189
+ // The chain's own drawing says which rows are which: this fake names itself in every row.
1190
+ const chain = {
1191
+ renderShell: 'self',
1192
+ renderCall: () => ({ render: (width) => [`host call ${width}`], invalidate() {} }),
1193
+ renderResult: () => ({ render: (width) => [`host result ${width}`], invalidate() {} }),
1194
+ };
1195
+ const call = (slot) => slot.renderCall({ operation: 'explore' }, plainTheme, { isPartial: false }).render(40);
1196
+ const result = (slot) => slot.renderResult(textResult('output'), { isPartial: false }, plainTheme, { args: { operation: 'explore' } }).render(40);
990
1197
  for (const answer of answers) {
991
1198
  publishBridge(() => answer);
992
1199
  const resolver = cardFor();
993
1200
  for (const tool of [CODEGRAPH_TOOL, CODEGRAPH_MCP_TOOL, 'bash']) {
994
- assert.equal(resolver(tool, () => HOST_BASH), HOST_BASH, `${tool} under ${JSON.stringify(answer)}`);
1201
+ // The card is claimed — Pi resolves it once and would never ask again — and every
1202
+ // answer but `activity` draws the chain's own rows, on every paint.
1203
+ const slot = resolver(tool, () => chain);
1204
+ assert.equal(slot?.renderShell, 'self', `${tool} under ${JSON.stringify(answer)}`);
1205
+ assert.deepEqual(call(slot), ['host call 40'], `${tool} under ${JSON.stringify(answer)}`);
1206
+ assert.deepEqual(result(slot), ['host result 40'], `${tool} under ${JSON.stringify(answer)}`);
995
1207
  }
996
1208
  }
997
1209
  publishBridge(() => { throw new Error('bridge exploded'); });
998
- assert.equal(cardFor()(CODEGRAPH_TOOL, () => HOST_BASH), HOST_BASH, 'a throwing reader is a no');
1210
+ assert.deepEqual(call(cardFor()(CODEGRAPH_TOOL, () => chain)), ['host call 40'], 'a throwing reader is a no');
999
1211
  publishBridge(ACTIVITY_ON);
1000
1212
  });
1001
1213
 
1002
- test('S11: with no reader at all the card claims nothing, and a host without the hook registers nothing', () => {
1214
+ test('S11: with no reader at all the chain\'s rows are drawn, and a host without the hook registers nothing', () => {
1215
+ const silent = (slot) => slot.renderCall({ operation: 'explore' }, plainTheme, { isPartial: false }).render(40);
1003
1216
  globalThis[BRIDGE_API_SLOT] = { schema: 'gentle-shell-bridge/api', version: 1 };
1004
- assert.equal(cardFor()(CODEGRAPH_TOOL, () => HOST_BASH), HOST_BASH, 'an older bridge has no switch to follow');
1217
+ assert.deepEqual(silent(cardFor()(CODEGRAPH_TOOL, () => HOST_BASH)), [], 'an older bridge has no switch to follow, so the host draws its own rows');
1005
1218
  delete globalThis[BRIDGE_API_SLOT];
1006
- assert.equal(cardFor()(CODEGRAPH_TOOL, () => HOST_BASH), HOST_BASH, 'no bridge, no switch, no card');
1219
+ assert.deepEqual(silent(cardFor()(CODEGRAPH_TOOL, () => HOST_BASH)), [], 'no bridge, no switch, so the host still draws its own rows');
1007
1220
  publishBridge(ACTIVITY_ON);
1008
1221
  const { registerCodegraphCard } = require('../lib/codegraph-card.js');
1009
1222
  assert.deepEqual(registerCodegraphCard({}, {}), { registered: false, resolver: undefined }, 'no host hook, no registration');
@@ -4,11 +4,22 @@
4
4
  // conversation's card style never reaches them. While the bridge's `Card activity` line answers
5
5
  // `activity` for the tool being drawn, this package draws them on its own card substrate
6
6
  // (`lib/shell-card.js`), in whichever style the shell has chosen. Any other answer — and the
7
- // absence of an answer — leaves Pi's own drawing exactly as it was.
7
+ // absence of an answer — draws what Pi draws for a tool with no renderer, inside the card that
8
+ // was already mounted.
9
+ //
10
+ // The answer is read on EVERY paint, inside the component the host already mounted, because Pi
11
+ // resolves a tool's renderers once (`interactive-mode.js`: `getRegisteredToolDefinition` goes
12
+ // into `ToolExecutionComponent` at construction) and never asks again. That is what makes a
13
+ // flipped `Card activity` line repaint the cards already on screen, exactly as it does for
14
+ // `bash`, and the cases below drive it that way: one mounted component, repainted.
8
15
  //
9
16
  // Every case goes through the public surface: the resolver, the slots it returns and the
10
17
  // rows a component draws for a width. The text seam and the themes are the fakes
11
18
  // `tools/file-card.test.js` uses; the bridge is the published object a process-wide slot holds.
19
+ //
20
+ // The rows the card hands back while the line says anything else are compared byte for byte
21
+ // with Pi's own drawing, reproduced here from the host's source (`tool-execution.js`,
22
+ // `render-utils.js`) and independently of this package's implementation.
12
23
  const assert = require('node:assert/strict');
13
24
  const { after, afterEach, beforeEach, test } = require('node:test');
14
25
 
@@ -115,9 +126,91 @@ function assertFramed(rows, width) {
115
126
  for (const row of rows) assert.equal(metrics.visibleWidth(unpaint(row)), width, `"${unpaint(row)}" is not ${width} wide`);
116
127
  }
117
128
 
129
+ // ---- Pi's own drawing for a tool with a definition and no renderer ----
130
+ //
131
+ // Reproduced from the host's source and independently of this package: `contentBox` is
132
+ // `new Box(1, 1, bgFn)` with the `outputPad` columns of horizontal padding, `addChild`s
133
+ // `createCallFallback()` — `formatToolCallWithArgs(toolName, args, theme, expanded)` — and,
134
+ // once the result exists, `createResultFallback()`; `Box.render` draws one painted blank row
135
+ // above, the children at `width - pad * 2` padded to the full width, and one blank below.
136
+ const hostTheme = {
137
+ fg: (role, value) => `<${role}>${value}</${role}>`,
138
+ bg: (role, value) => `<${role}>${value}</${role}>`,
139
+ bold: (value) => `<bold>${value}</bold>`,
140
+ };
141
+
142
+ /** `formatToolCallWithArgs`: the bold name, then `key=value` pairs — or one `key: value` row each. */
143
+ function piCallText(tool, args, expanded) {
144
+ const header = hostTheme.fg('toolTitle', hostTheme.bold(tool));
145
+ if (args === null || args === undefined) return header;
146
+ const entries = typeof args === 'object' && !Array.isArray(args) ? Object.entries(args) : [['args', args]];
147
+ if (entries.length === 0) return header;
148
+ if (expanded) {
149
+ const lines = entries.map(([key, value]) => {
150
+ const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2) ?? String(value);
151
+ return ` ${key}: ${text.replace(/\t/g, ' ').replace(/\r/g, '').split('\n').join('\n ')}`;
152
+ });
153
+ return `${header}\n${hostTheme.fg('muted', lines.join('\n'))}`;
154
+ }
155
+ const pairs = entries.map(([key, value]) => `${key}=${JSON.stringify(value) ?? String(value)}`).join(' ');
156
+ const preview = pairs.length > 100 ? `${pairs.slice(0, 97)}...` : pairs;
157
+ return `${header} ${hostTheme.fg('muted', preview)}`;
158
+ }
159
+
160
+ // The host's own readers for a result's text (`dist/utils/ansi.js`: `stripAnsi`;
161
+ // `dist/utils/shell.js`: `sanitizeBinaryOutput`; then `\r` goes), transcribed from the host's
162
+ // source so the fallback rows can be compared byte for byte. Note what the host KEEPS: DEL
163
+ // (U+007F) is not in its list, and U+FFF9–U+FFFB are removed like binary controls.
164
+ const PI_ANSI = /(?:\u001B\][\s\S]*?(?:\u0007|\u001B\\|\u009C))|(?:(?:\u001B\[|\u009B)[<=>]|[\u001B\u009B][[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?)[\dA-PR-TZcf-nq-uy=><~]/g;
165
+ const PI_BINARY = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFF9-\uFFFB]/g;
166
+ const piText = (value) => value.replace(PI_ANSI, '').replace(PI_BINARY, '').replace(/\r/g, '');
167
+
168
+ /** `createResultFallback`: the result's text, ten rows collapsed, and the host's own expand hint. */
169
+ function piResultText(result, context) {
170
+ const output = result.content.filter((part) => part.type === 'text').map((part) => piText(part.text || '')).join('\n');
171
+ if (output === '') return undefined;
172
+ const lines = output.split('\n');
173
+ const shown = context.expanded === true ? lines : lines.slice(0, 10);
174
+ const remaining = lines.length - shown.length;
175
+ const text = shown.map((line) => hostTheme.fg('toolOutput', line)).join('\n');
176
+ if (remaining <= 0) return text;
177
+ return `${text}${hostTheme.fg('muted', `\n... (${remaining} more lines,`)} ${context.keyHint('app.tools.expand', 'to expand')}${hostTheme.fg('muted', ')')}`;
178
+ }
179
+
180
+ /** `Text(text, 0, 0).render(width)`: tabs are three spaces, wrapped, every row padded to the width. */
181
+ function piTextRows(text, width) {
182
+ if (text.trim() === '') return [];
183
+ return metrics.wrapTextWithAnsi(text.replace(/\t/g, ' '), Math.max(1, width))
184
+ .map((row) => row + ' '.repeat(Math.max(0, width - metrics.visibleWidth(row))));
185
+ }
186
+
187
+ /** The host's box around the given children, exactly as `Box.render` draws it for this state. */
188
+ function piBox(childTexts, width, context) {
189
+ const pad = context.outputPad ?? 1;
190
+ const role = context.isPartial !== false ? 'toolPendingBg' : context.isError === true ? 'toolErrorBg' : 'toolSuccessBg';
191
+ const contentWidth = Math.max(1, width - pad * 2);
192
+ const rows = childTexts.flatMap((text) => piTextRows(text, contentWidth));
193
+ if (rows.length === 0) return [];
194
+ const painted = (line) => hostTheme.bg(role, line + ' '.repeat(Math.max(0, width - metrics.visibleWidth(line))));
195
+ return [painted(''), ...rows.map((row) => painted(' '.repeat(pad) + row)), painted('')];
196
+ }
197
+
198
+ /** The key hint the host paints into a fallback result, the same seam the cards read. */
199
+ const keyHint = (_id, text) => `[${text}]`;
200
+ const settled = { isPartial: false, expanded: false, outputPad: 1, keyHint };
201
+
202
+ /** What Pi draws for one settled job card: the call's fallback and the result's, in one box. */
203
+ function piSettledRows(tool, args, text, context, width) {
204
+ const result = { content: [{ type: 'text', text }], details: {} };
205
+ const children = [piCallText(tool, args, context.expanded === true)];
206
+ const fallback = piResultText(result, context);
207
+ if (fallback !== undefined) children.push(fallback);
208
+ return piBox(children, width, context);
209
+ }
210
+
118
211
  // ---- the one switch ----
119
212
 
120
- test('the card is drawn only while the Card activity line answers activity; every other answer leaves Pi\'s own drawing', () => {
213
+ test('every answer but activity draws what Pi draws for a tool with no renderer, byte for byte', () => {
121
214
  const answers = [
122
215
  ['no bridge published', undefined],
123
216
  ['the bridge\'s native answer', { kind: 'native' }],
@@ -126,30 +219,133 @@ test('the card is drawn only while the Card activity line answers activity; ever
126
219
  ['another plugin\'s design', { kind: 'design', design: { id: 'acme.tools' } }],
127
220
  ['an answer nothing can read', 'garbage'],
128
221
  ];
222
+ const args = { command: COMMAND, label: LABEL };
129
223
  for (const [name, answer] of answers) {
130
224
  if (answer !== undefined) publishBridge(answer);
131
- for (const tool of JOB_TOOLS) assert.equal(slots(jobsResolver(), tool), PI_DEFAULT, `${name}: ${tool}`);
225
+ for (const tool of JOB_TOOLS) {
226
+ const callArgs = tool === 'job_stop' ? { job_id: 'job-2' } : tool === 'job_list' ? {} : args;
227
+ const resolver = jobsResolver();
228
+ const call = slots(resolver, tool).renderCall(callArgs, hostTheme, { args: callArgs, ...settled }).render(70);
229
+ const result = slots(resolver, tool)
230
+ .renderResult({ content: [{ type: 'text', text: STARTED }], details: {} }, settled, hostTheme, { args: callArgs, state: {}, ...settled })
231
+ .render(70);
232
+ assert.deepEqual([...call, ...result], piSettledRows(tool, callArgs, STARTED, settled, 70), `${name}: ${tool}`);
233
+ }
132
234
  delete globalThis[BRIDGE_API_SLOT];
133
235
  }
134
236
  // A bridge too old to carry the reader, and one whose reader throws, are no answer either.
135
237
  globalThis[BRIDGE_API_SLOT] = { schema: 'gentle-shell-bridge/api', version: 1, VERSION: '0.6.0', registerToolDesign: () => () => {} };
136
- assert.equal(slots(jobsResolver(), 'bash_background'), PI_DEFAULT);
238
+ assert.deepEqual(
239
+ [...callRows(jobsResolver(), 'bash_background', args, hostTheme, 70, settled), ...resultRows(jobsResolver(), 'bash_background', args, STARTED, settled, hostTheme, 70, settled)],
240
+ piSettledRows('bash_background', args, STARTED, settled, 70),
241
+ 'a bridge older than the reader',
242
+ );
137
243
  publishBridge(() => { throw new Error('boom'); });
138
- assert.equal(slots(jobsResolver(), 'bash_background'), PI_DEFAULT);
244
+ assert.deepEqual(
245
+ [...callRows(jobsResolver(), 'bash_background', args, hostTheme, 70, settled), ...resultRows(jobsResolver(), 'bash_background', args, STARTED, settled, hostTheme, 70, settled)],
246
+ piSettledRows('bash_background', args, STARTED, settled, 70),
247
+ 'a reader that throws',
248
+ );
249
+ });
250
+
251
+ test('a call still running keeps the host\'s box closed below it, because no result follows yet', () => {
252
+ publishBridge({ kind: 'native' });
253
+ const args = { command: COMMAND };
254
+ const running = callRows(jobsResolver(), 'bash_background', args, hostTheme, 60, { isPartial: true, outputPad: 1 });
255
+ assert.deepEqual(running, piBox([piCallText('bash_background', args, false)], 60, { isPartial: true, outputPad: 1 }));
256
+ assert.equal(metrics.visibleWidth(unpaint(running[0])), 60, 'the box paints its blank rows to the whole width');
139
257
  });
140
258
 
141
- test('while activity is selected the four job tools get a self-framed card and the bridge is asked per tool', () => {
259
+ test('a result that states nothing leaves the host\'s box closed, with no row of its own', () => {
260
+ publishBridge({ kind: 'native' });
261
+ const args = { job_id: 'job-2' };
262
+ const resolver = jobsResolver();
263
+ const call = callRows(resolver, 'job_stop', args, hostTheme, 50, settled);
264
+ const result = resultRows(resolver, 'job_stop', args, '', settled, hostTheme, 50, settled);
265
+ assert.deepEqual([...call, ...result], piSettledRows('job_stop', args, '', settled, 50), 'the host draws the box around the call alone');
266
+ assert.deepEqual(result, [piBox([piCallText('job_stop', args, false)], 50, settled).at(-1)], 'the result half is that box\'s closing row');
267
+ });
268
+
269
+ /**
270
+ * One pass of Pi's own component: the result half is BUILT when its update arrives (before the
271
+ * pass), then the pass renders the call and the result inside the one box. The card is driven in
272
+ * that same order, so a mark made while painting cannot hide behind the next frame.
273
+ */
274
+ function piPass(resolver, tool, args, text, context, width) {
275
+ const state = {};
276
+ const options = { isPartial: context.isPartial === true, expanded: context.expanded === true };
277
+ const result = slots(resolver, tool).renderResult({ content: [{ type: 'text', text }], details: {} }, options, hostTheme, { args, state, ...context });
278
+ const call = slots(resolver, tool).renderCall(args, hostTheme, { args, state, ...context });
279
+ return [...call.render(width), ...result.render(width)];
280
+ }
281
+
282
+ test('a PARTIAL result closes the host\'s box once, exactly as the host draws it', () => {
283
+ publishBridge({ kind: 'native' });
284
+ const partial = { isPartial: true, expanded: false, outputPad: 2, keyHint };
285
+ const args = { command: 'tail -f app.log', label: 'app log' };
286
+ const resolver = jobsResolver();
287
+ assert.deepEqual(piPass(resolver, 'monitor', args, STARTED, partial, 84), piSettledRows('monitor', args, STARTED, partial, 84), 'the call waits while its result streams');
288
+ // An empty partial result is no child at all: the box is the one around the call.
289
+ assert.deepEqual(piPass(resolver, 'monitor', args, '', partial, 84), piSettledRows('monitor', args, '', partial, 84));
290
+ });
291
+
292
+ test('the host\'s own reader sanitizes a result, byte for byte', () => {
293
+ publishBridge({ kind: 'native' });
294
+ // A CSI colour, a BEL, the interlinear annotations the host strips, a CR and a DEL — which
295
+ // the host's own list does NOT remove (`sanitizeBinaryOutput`).
296
+ const raw = 'first \u001B[31mred\u001B[0m\uFFFB row\u0007\r\nsecond\u007F row';
297
+ const args = { command: COMMAND };
298
+ const resolver = jobsResolver();
299
+ assert.deepEqual(piPass(resolver, 'bash_background', args, raw, settled, 70), piSettledRows('bash_background', args, raw, settled, 70));
300
+ const drawn = piPass(resolver, 'bash_background', args, raw, settled, 70).join('\n');
301
+ assert.doesNotMatch(unpaint(drawn), /\u001B|\uFFFB|\u0007/u, 'the host strips these');
302
+ assert.match(unpaint(drawn), /second\u007F row/u, 'and the host keeps DEL, so the card keeps it too');
303
+ });
304
+
305
+ test('the four job tools are always the card\'s, and the line is read on every paint, never at build time', () => {
142
306
  const asked = [];
143
307
  publishBridge(ACTIVITY, asked);
144
308
  const resolver = jobsResolver();
145
- for (const tool of JOB_TOOLS) {
146
- const drawn = slots(resolver, tool);
309
+ const slots_ = JOB_TOOLS.map((tool) => slots(resolver, tool));
310
+ assert.deepEqual(asked, [], 'building the card asks nothing: Pi would never ask again');
311
+ for (const [index, tool] of JOB_TOOLS.entries()) {
312
+ const drawn = slots_[index];
147
313
  assert.notEqual(drawn, PI_DEFAULT, tool);
148
314
  assert.equal(drawn.renderShell, 'self', `${tool} frames itself`);
149
315
  assert.equal(typeof drawn.renderCall, 'function');
150
316
  assert.equal(typeof drawn.renderResult, 'function');
151
317
  }
152
- assert.deepEqual(asked, [...JOB_TOOLS]);
318
+ for (const [index, tool] of JOB_TOOLS.entries()) {
319
+ const args = tool === 'job_stop' ? { job_id: 'job-2' } : tool === 'job_list' ? {} : { command: COMMAND };
320
+ slots_[index].renderCall(args, plainTheme, { args, ...settled }).render(70);
321
+ assert.deepEqual(asked.at(-1), tool, `${tool} is asked on its own name`);
322
+ slots_[index].renderResult({ content: [{ type: 'text', text: STARTED }], details: {} }, settled, plainTheme, { args, state: {}, ...settled }).render(70);
323
+ assert.deepEqual(asked.at(-1), tool, `${tool}'s result asks the same question`);
324
+ }
325
+ assert.equal(asked.length, JOB_TOOLS.length * 2, 'one question per painted slot, and no other');
326
+ });
327
+
328
+ test('a mounted card repaints when the line flips, in both directions', () => {
329
+ const asked = [];
330
+ publishBridge(ACTIVITY, asked);
331
+ const resolver = jobsResolver();
332
+ const args = { command: COMMAND, label: LABEL };
333
+ // ONE card, mounted: the components the host built before any of this changed.
334
+ const call = slots(resolver, 'bash_background').renderCall(args, hostTheme, { args, ...settled });
335
+ const result = slots(resolver, 'bash_background')
336
+ .renderResult({ content: [{ type: 'text', text: STARTED }], details: {} }, settled, hostTheme, { args, state: {}, ...settled });
337
+ const on = { call: call.render(70), result: result.render(70) };
338
+ assert.match(unpaint(on.call[0]), /⧗ bash background · Release runs/u, 'the card is drawn while the line says activity');
339
+ // The line is turned off, and the SAME mounted components are repainted.
340
+ publishBridge({ kind: 'native' });
341
+ const off = { call: call.render(70), result: result.render(70) };
342
+ assert.deepEqual([...off.call, ...off.result], piSettledRows('bash_background', args, STARTED, settled, 70), 'flipped off, the rows are the host\'s own');
343
+ assert.doesNotMatch(unpaint(off.call.join('\n')), /⧗/u, 'the card\'s mark is gone');
344
+ // And back on, from the same two components.
345
+ publishBridge(ACTIVITY, asked);
346
+ assert.deepEqual(call.render(70), on.call, 'flipped back on, the card is drawn again, unchanged');
347
+ assert.deepEqual(result.render(70), on.result, 'the result half too');
348
+ assert.equal(asked.length, 4, 'each paint of each half asked the line once: two paints on, and two back on');
153
349
  });
154
350
 
155
351
  test('no other tool is ever claimed: bash, the file tools and an unknown tool come back as the chain resolved them', () => {