@notrico/pi-fold 0.0.0-stage → 3.0.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/LICENSE +21 -0
  3. package/README.md +71 -2
  4. package/docs/implementation.md +47 -0
  5. package/docs/performance.md +118 -0
  6. package/docs/renderer-reference.md +110 -0
  7. package/index.ts +53 -0
  8. package/package.json +55 -4
  9. package/scripts/performance-review.mjs +273 -0
  10. package/scripts/preview-inspection.mjs +9 -0
  11. package/scripts/preview-work-strip.mjs +101 -0
  12. package/scripts/preview.mjs +232 -0
  13. package/scripts/retained-memory-review.mjs +46 -0
  14. package/scripts/test.mjs +21 -0
  15. package/src/action-intent.ts +93 -0
  16. package/src/display-card.ts +66 -0
  17. package/src/display-line-cache.ts +26 -0
  18. package/src/display-mode.ts +33 -0
  19. package/src/fold-command.ts +61 -0
  20. package/src/inspection.ts +87 -0
  21. package/src/modern-code-content.ts +131 -0
  22. package/src/modern-code-pane.ts +103 -0
  23. package/src/modern-native-tools.ts +79 -0
  24. package/src/modern-prompts-adapter.ts +41 -0
  25. package/src/modern-prompts.ts +185 -0
  26. package/src/modern-recorded-pane.ts +68 -0
  27. package/src/modern-rich-text.ts +48 -0
  28. package/src/modern-skill-prompts.ts +152 -0
  29. package/src/modern-subagent-groups.ts +158 -0
  30. package/src/modern-subagent-messages.ts +176 -0
  31. package/src/modern-subagent-spacing.ts +35 -0
  32. package/src/modern-subagents.ts +52 -0
  33. package/src/modern-thinking-adapter.ts +85 -0
  34. package/src/modern-thinking.ts +258 -0
  35. package/src/modern-tool-content.ts +28 -0
  36. package/src/modern-tool-images.ts +63 -0
  37. package/src/modern-tool-pane.ts +219 -0
  38. package/src/modern-tools.ts +509 -0
  39. package/src/modern-workflows.ts +212 -0
  40. package/src/native-method-chain.ts +31 -0
  41. package/src/permission-presentation.ts +280 -0
  42. package/src/recorded-summary.ts +13 -0
  43. package/src/work-strip-subagents.ts +221 -0
  44. package/src/work-strip-view.ts +112 -0
  45. package/src/work-strip.ts +443 -0
  46. package/tests/action-intent.test.mjs +44 -0
  47. package/tests/codemode.test.mjs +388 -0
  48. package/tests/display-cache-lifecycle.test.mjs +55 -0
  49. package/tests/display-line-cache.test.mjs +48 -0
  50. package/tests/display-mode.test.mjs +25 -0
  51. package/tests/fixtures/preview-fixture.ts +81 -0
  52. package/tests/fold-command.test.mjs +150 -0
  53. package/tests/fold-shortcut.test.mjs +143 -0
  54. package/tests/input-focus.test.mjs +95 -0
  55. package/tests/inspection-wheel.test.mjs +73 -0
  56. package/tests/inspection.test.mjs +50 -0
  57. package/tests/mixed-thinking.test.mjs +371 -0
  58. package/tests/modern-prompts.test.mjs +84 -0
  59. package/tests/modern-skill-prompts.test.mjs +174 -0
  60. package/tests/modern-subagent-groups.test.mjs +132 -0
  61. package/tests/modern-subagent-messages.test.mjs +137 -0
  62. package/tests/modern-thinking.test.mjs +202 -0
  63. package/tests/modern-tools.test.mjs +961 -0
  64. package/tests/modern-workflows.test.mjs +189 -0
  65. package/tests/ordinary-prompts.test.mjs +167 -0
  66. package/tests/permission-presentation.test.mjs +257 -0
  67. package/tests/preview-example.test.mjs +171 -0
  68. package/tests/reload-lifecycle.test.mjs +161 -0
  69. package/tests/subagent-spacing.test.mjs +34 -0
  70. package/tests/test-runtime.mjs +58 -0
  71. package/tests/work-strip-final-surface.test.mjs +321 -0
  72. package/tests/work-strip-hierarchy.test.mjs +258 -0
  73. package/tests/work-strip-preview.test.mjs +120 -0
  74. package/tests/work-strip-spacing.test.mjs +208 -0
  75. package/tests/work-strip-subagents.test.mjs +236 -0
  76. package/tests/work-strip.test.mjs +148 -0
@@ -0,0 +1,120 @@
1
+ import assert from 'node:assert/strict';
2
+ import path from 'node:path';
3
+ import {pathToFileURL} from 'node:url';
4
+ import {createWorkStripPreview} from '../scripts/preview-work-strip.mjs';
5
+ const preview=await createWorkStripPreview({stepMs:20});
6
+ const {core,runtime,manager}=preview;
7
+ const {visibleWidth}=await import(pathToFileURL(path.join(preview.runtimePath,'node_modules/@earendil-works/pi-tui/dist/index.js')));
8
+ const {theme,initTheme}=await import(pathToFileURL(path.join(preview.runtimePath,'node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js')));
9
+ initTheme('dark',false);
10
+ const strip=s=>s.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]/g,'');
11
+ const errors=[];
12
+ runtime.session.extensionRunner.onError(error=>errors.push(error));
13
+ const ui=new core.InteractiveMode(runtime,{tuiMode:'fullscreen'});
14
+ ui.updateTerminalTitle=()=>{};
15
+ Object.defineProperty(ui.ui,'isFollowingOutput',{get:()=>true});
16
+ const inputs=[];
17
+ runtime.session.extensionRunner.setUIContext({...ui.createExtensionUIContext(),theme,onTerminalInput(fn){inputs.push(fn);return()=>{};},setHiddenThinkingLabel(){},setStatus(){},setWidget(){},notify(){}},'tui');
18
+ const paint=()=>strip(ui.chatContainer.render(110).join('\n'));
19
+ let off, offLive;
20
+ try{
21
+ // Native reload ordering: replay first, extension session_start second.
22
+ ui.renderSessionEntries(manager.getBranch());
23
+ await runtime.session.extensionRunner.emit({type:'session_start',reason:'resume'});
24
+ // Native startup refreshes the UI after extension session_start. Rebuild
25
+ // cached custom-message renderers too, as the terminal's invalidation does.
26
+ ui.chatContainer.invalidate();
27
+ const before=paint();
28
+ const lines=before.split('\n');
29
+ const dddLine=lines.findIndex(line=>line.includes('DDD · Five recorded maintenance'));
30
+ assert.equal(lines[dddLine-1].trim(),'','DDD has the same one-line separation as decision rows');
31
+ const projected=ui.chatContainer[Symbol.for('compact-renderer:projected-children:v1')];
32
+ const canonical=ui.chatContainer.children;
33
+ const skill=canonical.find(row=>row.constructor.name==='SkillInvocationMessageComponent');
34
+ const skillPosition=projected.indexOf(skill);
35
+ assert.ok(skillPosition>0,'native skill remains the combined prompt anchor');
36
+ assert.equal(projected[skillPosition-1],canonical[canonical.indexOf(skill)-1],'folding preserves the outside gap before the combined prompt');
37
+ const combined = strip(skill.render(110).join('\n'));
38
+ assert.match(combined, /▸ \/skill:fixture-review/);
39
+ assert.match(combined, /Show the native skill card and one final successful action/);
40
+ assert.doesNotMatch(combined, /\[skill\]|ctrl\+o|Review the synthetic preview/);
41
+ assert.equal((before.match(/Show the native skill card and one final successful action/g)||[]).length,1,'combined user text appears exactly once');
42
+ const promptFill = theme.bg('userMessageBg', '').replace(/\x1b\[49m$/, '');
43
+ assert.ok(skill.render(110).every(line => line.includes(promptFill)), 'combined skill and message share the blue prompt surface');
44
+ skill.handleMouse({type:'click',button:'left',x:3,y:1,width:110});
45
+ assert.match(strip(skill.render(110).join('\n')), /Review the synthetic preview/, 'click reveals the recorded skill body');
46
+ skill.handleMouse({type:'click',button:'left',x:3,y:1,width:110});
47
+ for(let i=1;i<projected.length;i++) if(projected[i] instanceof core.UserMessageComponent) {
48
+ assert.equal(projected[i-1].constructor.name,'Spacer','next prompt keeps an outside gap after folded work');
49
+ }
50
+ const header=projected.find(row=>row.constructor.name==='WorkStripHeader');
51
+ assert.ok(header.render(110).join('\n').includes(theme.fg('muted','▸ '+header.title)),'work-strip label uses quiet secondary contrast');
52
+ assert.match(strip(header.render(110).join('\n')),/Worked for.*─{4}/,'work strip has a visible divider');
53
+ for(const width of [1,2,4,20,80,160]) for(const line of header.render(width)) assert.ok(visibleWidth(line)<=width,'divider stays within the terminal width');
54
+ header.render(110);
55
+ assert.equal(header.handleMouse({type:'click',button:'left',x:30,y:1})?.handled,true,'divider is part of the disclosure target');
56
+ assert.equal(header.open,true);
57
+ header.handleMouse({type:'click',button:'left',x:30,y:1});
58
+ assert.equal((before.match(/▸ Worked for/g)||[]).length,3);
59
+ assert.match(before,/Question · Answered/); assert.match(before,/DDD · Five recorded maintenance/);
60
+ const workColumn = lines.find(line => line.includes('Worked for')).search(/\S/);
61
+ for (const label of ['Question · Answered', 'worker · Decision answered', 'Subagent · researcher', 'Subagent · scout', 'DDD · Five recorded maintenance']) {
62
+ const row = lines.find(line => line.includes(label));
63
+ assert.ok(row, `preview includes ${label}`);
64
+ assert.equal(row.search(/\S/), workColumn + 2, `${label} is indented beneath the collapsed work strip`);
65
+ }
66
+ assert.doesNotMatch(before,/Run Node.js script|Subagent workflow|Synthetic instruction 70|Read files/);
67
+ assert.match(before,/Work-strip preview/);
68
+ assert.match(before,/⋯ Show more/,'long prompt has generic quiet disclosure');
69
+ assert.match(before,/Do not execute tools or access any external data/,'long prompt keeps its ending');
70
+ assert.doesNotMatch(before,/Preserve recorded sample 1,/,'opening excerpt does not expose a partial list');
71
+ const neutral = theme.bg('toolPendingBg', '').replace(/\x1b\[49m$/, '');
72
+ for (const label of ['Recorded preview decisions', 'Work-strip preview:', 'This direct reply has no work strip']) {
73
+ const line = ui.chatContainer.render(110).find(row => strip(row).includes(label));
74
+ assert.ok(line?.includes(neutral), `${label} uses the final reply surface in the real runtime`);
75
+ }
76
+ const finalRows = ui.chatContainer.render(110);
77
+ const directStart = finalRows.findIndex(row => strip(row).includes('This direct reply has no work strip'));
78
+ const finalEnd = finalRows.findIndex((row, index) => index >= directStart && !strip(row).trim());
79
+ for (const index of [directStart - 1, finalEnd]) {
80
+ assert.equal(strip(finalRows[index]).trim(), '', 'final reply has blank internal padding at both boundaries');
81
+ assert.ok(finalRows[index].includes(neutral), 'final padding uses the same neutral fill as the content');
82
+ }
83
+ // Final mixed thinking is folded, while final Markdown remains native.
84
+ ui.isInitialized=true;
85
+ off=runtime.session.subscribe(event=>ui.handleEvent(event));
86
+ const live=[];
87
+ offLive=runtime.session.subscribe(event=>{
88
+ if(!['message_start','message_end'].includes(event.type) || event.message.role!=='assistant')return;
89
+ const label=event.message.content.find(block=>block.type==='text' && block.text)?.text;
90
+ if(!label)return;
91
+ const rendered=paint().split('\n');
92
+ const projected=ui.chatContainer[Symbol.for('compact-renderer:projected-children:v1')];
93
+ const row=ui.chatContainer.children.findLast(row=>row instanceof core.AssistantMessageComponent);
94
+ const view=projected.find(item=>item===row || item.children?.[0]===row);
95
+ live.push({type:event.type,label,row,view,column:rendered.findLast(line=>line.includes(label.slice(0,40)))?.search(/\S/)});
96
+ });
97
+ const playing=preview.play();
98
+ await new Promise(resolve=>setTimeout(resolve,30));
99
+ assert.match(paint(),/Working · 0s · Reading the recorded sample labels/);
100
+ assert.match(paint(),/Reading the recorded sample labels/);
101
+ if(process.env.PI_PREVIEW_STATUSLINE) {
102
+ assert.ok(ui.customFooter,'matching native footer mounted');
103
+ assert.doesNotMatch(strip(ui.customFooter.render(160).join('\n')),/Working ·/,'work strip owns execution status');
104
+ }
105
+ await playing; await new Promise(resolve=>setTimeout(resolve,150));
106
+ assert.equal(live.length,8,'all four invented replies render during streaming and after message_end');
107
+ for(const frame of live) {
108
+ assert.equal(frame.view?.constructor.name,'WorkChild',`${frame.label} stays indented during ${frame.type}`);
109
+ assert.equal(frame.column,workColumn+2,'live commentary uses the same child column as recorded work');
110
+ }
111
+ for(let i=0;i<live.length;i+=2) assert.equal(live[i].view,live[i+1].view,'message_end does not shift the current reply');
112
+ const after=paint();
113
+ assert.equal((after.match(/▸ Worked for/g)||[]).length,4);
114
+ assert.doesNotMatch(after,/Comparing the recorded units|Checking the recorded result|Compare the invented samples|Thinking/);
115
+ assert.match(after,/The invented samples agree/);
116
+ assert.ok(ui.chatContainer.render(110).find(row => strip(row).includes('The invented samples agree'))?.includes(neutral), 'live final reply receives its surface after settlement');
117
+ assert.equal(manager.getBranch().filter(e=>e.customType==='compact-renderer:work-settled:v1').length,4);
118
+ assert.deepEqual(errors,[]);
119
+ console.log('Work strip real runtime preview, native reload order, live playback and final folding passed');
120
+ }finally{offLive?.(); off?.(); ui.ui.stop(); await preview.cleanup(); ui.footerDataProvider.dispose();}
@@ -0,0 +1,208 @@
1
+ import assert from 'node:assert/strict';
2
+ import { core, loadSource, themeModule, tui, stripAnsi } from './test-runtime.mjs';
3
+
4
+ const { registerWorkStrip } = await loadSource('./work-strip.ts');
5
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
6
+ const { projectedChildren, workEvidenceType } = await loadSource('./work-strip-view.ts');
7
+
8
+ // Exercise the native child tree. A colored card's blank padding is not an
9
+ // outside transcript gap, so spacing assertions use component identity.
10
+ function fixture() {
11
+ const hooks = new Map(), bus = new Map();
12
+ const subscribe = (map, name, fn) => {
13
+ if (!map.has(name)) map.set(name, new Set());
14
+ map.get(name).add(fn);
15
+ return () => map.get(name).delete(fn);
16
+ };
17
+ const manager = core.SessionManager.inMemory('/synthetic-spacing');
18
+ const pi = {
19
+ on: (name, fn) => subscribe(hooks, name, fn),
20
+ events: {
21
+ on: (name, fn) => subscribe(bus, name, fn),
22
+ emit: (name, value) => { for (const fn of [...(bus.get(name) || [])]) fn(value); },
23
+ },
24
+ getAllTools: () => [],
25
+ appendEntry: (kind, data) => manager.appendCustomEntry(kind, data),
26
+ };
27
+ const mode = createDisplayMode();
28
+ const dispose = registerWorkStrip(pi, mode).dispose;
29
+ const ui = { isFollowingOutput: true, requestRender() {}, theme: themeModule.theme };
30
+ const ctx = { mode: 'tui', hasUI: true, ui, sessionManager: manager, isIdle: () => true };
31
+ const display = {
32
+ chatContainer: new tui.Container(), ui, pendingTools: new Map(), outputPad: 1,
33
+ toolOutputExpanded: false, hideThinkingBlock: true, sessionManager: manager,
34
+ session: { extensionRunner: {
35
+ getMessageRenderer() {},
36
+ getEntryRenderer: () => () => new tui.Text('CUSTOM_ENTRY', 0, 0),
37
+ } },
38
+ getUserMessageText: message => message.content,
39
+ getMarkdownThemeWithSettings: () => themeModule.getMarkdownTheme(),
40
+ getMarkdownTransformers: () => [], editor: { addToHistory() {} },
41
+ };
42
+ const add = message => {
43
+ message.timestamp ??= 1000 + manager.getBranch().length;
44
+ const before = display.chatContainer.children.length;
45
+ manager.appendMessage(message);
46
+ core.InteractiveMode.prototype.addMessageToChat.call(display, message);
47
+ return display.chatContainer.children.slice(before);
48
+ };
49
+ const assistant = text => add({ role: 'assistant', content: [{ type: 'text', text }], stopReason: 'stop' }).at(-1);
50
+ const user = add({ role: 'user', content: 'Initial prompt.' }).at(-1);
51
+ const userId = manager.getBranch().at(-1).id;
52
+ const activity = new core.ToolExecutionComponent('read', 'spacing-activity', {}, { outputPad: 1 }, undefined, ui, '/synthetic-spacing');
53
+ activity.setArgsComplete(); activity.updateResult({ content: [{type:'text',text:'HIDDEN_ACTIVITY'}], isError:false });
54
+ display.chatContainer.addChild(activity);
55
+ const commentary = assistant('HIDDEN_COMMENTARY');
56
+ const final = assistant('VISIBLE_FINAL');
57
+ const finalId = manager.getBranch().at(-1).id;
58
+ manager.appendCustomEntry(workEvidenceType, {
59
+ version: 1, userId, finalId, endId: finalId,
60
+ startedAt: 1000, endedAt: 2000, outcome: 'completed',
61
+ });
62
+ const paint = () => {
63
+ const rendered = display.chatContainer.render(100);
64
+ return { rows: display.chatContainer[projectedChildren], text: stripAnsi(rendered.join('\n')) };
65
+ };
66
+ const start = () => { for (const fn of [...(hooks.get('session_start') || [])]) fn({}, ctx); return paint(); };
67
+ return { add, assistant, display, manager, mode, dispose, paint, start, user, commentary, final, ui };
68
+ }
69
+
70
+ const skill = suffix => `<skill name="spacing" location="/synthetic-spacing/SKILL.md">\nSynthetic instructions.\n</skill>${suffix}`;
71
+ for (const suffix of ['\n\nFollow-up prompt.', '']) {
72
+ const f = fixture();
73
+ try {
74
+ const nativeRows = f.add({ role: 'user', content: skill(suffix) });
75
+ const [gap, card, userGap, user] = nativeRows;
76
+ assert.ok(gap instanceof tui.Spacer);
77
+ assert.ok(card instanceof core.SkillInvocationMessageComponent);
78
+ const { rows, text } = f.start();
79
+ assert.equal(rows[rows.indexOf(card) - 1], gap, 'skill retains its native outside spacer');
80
+ const finalView = rows.find(row => row.children?.[0] === f.final);
81
+ const finalLines = finalView.render(100).map(stripAnsi);
82
+ assert.equal(finalLines.length, f.final.render(100).length + 2, 'final card adds exactly two internal padding rows');
83
+ assert.equal(finalLines[0], '', 'final keeps its separate native outer gap');
84
+ assert.equal(finalLines[1], ' '.repeat(100), 'final owns its filled top padding');
85
+ assert.equal(finalLines.at(-1), ' '.repeat(100), 'final owns its filled bottom padding');
86
+ assert.deepEqual(gap.render(100), [''], 'following skill keeps an unfilled outside gap after the final bottom padding');
87
+ assert.equal(rows[rows.indexOf(finalView) + 1], gap, 'no extra component separates final card and following native gap');
88
+ if (suffix) {
89
+ assert.ok(userGap instanceof tui.Spacer);
90
+ assert.ok(user instanceof core.UserMessageComponent);
91
+ assert.equal(rows[rows.indexOf(user) - 1], userGap, 'skill and user keep their separate native gap');
92
+ } else assert.equal(nativeRows.length, 2, 'skill-only invocation has no synthetic user row');
93
+ assert.match(text, /VISIBLE_FINAL/);
94
+ assert.doesNotMatch(text, /HIDDEN_COMMENTARY/);
95
+ } finally { f.dispose(); }
96
+ }
97
+
98
+ for (const role of ['branchSummary', 'compactionSummary']) {
99
+ const f = fixture();
100
+ try {
101
+ const [gap, summary] = f.add({ role, summary: 'SUMMARY_CONTENT', tokensBefore: 100 });
102
+ assert.ok(gap instanceof tui.Spacer);
103
+ const { rows } = f.start();
104
+ assert.equal(rows[rows.indexOf(summary) - 1], gap, `${role} retains its native outside spacer`);
105
+ } finally { f.dispose(); }
106
+ }
107
+
108
+ for (const kind of ['custom', 'custom-entry', 'user-bash', 'question']) {
109
+ const f = fixture();
110
+ try {
111
+ let card;
112
+ if (kind === 'custom') card = f.add({ role: 'custom', customType: 'spacing-notice', display: true, content: 'CUSTOM_MESSAGE' }).at(-1);
113
+ if (kind === 'custom-entry') {
114
+ f.manager.appendCustomEntry('spacing-entry', {});
115
+ core.InteractiveMode.prototype.addCustomEntryToChat.call(f.display, f.manager.getBranch().at(-1));
116
+ card = f.display.chatContainer.children.at(-1);
117
+ }
118
+ if (kind === 'user-bash') card = f.add({ role: 'bashExecution', command: 'printf synthetic', output: 'USER_BASH', exitCode: 0, cancelled: false }).at(-1);
119
+ if (kind === 'question') {
120
+ card = new core.ToolExecutionComponent('ask_user_question', 'spacing-question', {}, { outputPad: 1 }, undefined, f.ui, '/synthetic-spacing');
121
+ card.setArgsComplete();
122
+ card.updateResult({ content: [{ type: 'text', text: 'QUESTION_ANSWER' }], isError: false });
123
+ f.display.chatContainer.addChild(card);
124
+ }
125
+ const internalGap = card.children[0];
126
+ assert.ok(internalGap instanceof tui.Spacer, `${kind} owns a native internal gap`);
127
+ const { rows } = f.start();
128
+ const index = rows.findIndex(row => row === card || row.constructor.name === 'WorkChild' && row.children[0] === card);
129
+ assert.ok(index >= 0, `${kind} remains visible`);
130
+ assert.ok(!(rows[index - 1] instanceof tui.Spacer), `${kind} receives no extra outside spacer`);
131
+ assert.equal(card.children[0], internalGap, `${kind} retains its own spacer`);
132
+ assert.equal(rows.filter(row => row instanceof tui.Spacer).length, 0, `${kind} adds no top-level gap`);
133
+ } finally { f.dispose(); }
134
+ }
135
+
136
+ {
137
+ const f = fixture();
138
+ try {
139
+ const hiddenGap = new tui.Spacer(2), trailingGap = new tui.Spacer(3);
140
+ const hidden = new core.ToolExecutionComponent('read', 'hidden-read', {}, { outputPad: 1 }, undefined, f.ui, '/synthetic-spacing');
141
+ hidden.setArgsComplete();
142
+ hidden.updateResult({ content: [{ type: 'text', text: 'HIDDEN_TOOL' }], isError: false });
143
+ f.display.chatContainer.addChild(hiddenGap);
144
+ f.display.chatContainer.addChild(hidden);
145
+ const notice = f.add({ role: 'custom', customType: 'spacing-notice', display: true, content: 'KEPT_NOTICE' }).at(-1);
146
+ f.display.chatContainer.addChild(trailingGap);
147
+ const canonical = [...f.display.chatContainer.children];
148
+ const { rows, text } = f.start();
149
+ assert.ok(!rows.includes(hiddenGap), 'gap owned by hidden row is discarded');
150
+ assert.ok(!rows.includes(hidden), 'completed read is folded');
151
+ assert.ok(!(rows[rows.indexOf(notice) - 1] instanceof tui.Spacer), 'hidden gap is not transferred to the next visible row');
152
+ assert.ok(!rows.includes(trailingGap), 'folded trailing gap is discarded');
153
+ assert.doesNotMatch(text, /HIDDEN_TOOL|HIDDEN_COMMENTARY/);
154
+ assert.deepEqual(f.display.chatContainer.children, canonical, 'folding preserves the canonical tree');
155
+ const header = rows.find(row => row.constructor.name === 'WorkStripHeader');
156
+ header.expand();
157
+ const open = f.paint();
158
+ assert.deepEqual(open.rows.filter(row => row !== header).map(row => row.children?.length === 1 && canonical.includes(row.children[0]) ? row.children[0] : row), canonical, 'expanded projection keeps canonical row identity and order');
159
+ assert.match(open.text, /HIDDEN_TOOL|HIDDEN_COMMENTARY/);
160
+ f.mode.setEnabled(false);
161
+ const native = f.paint();
162
+ assert.equal(native.rows, undefined, 'compact-off uses the native render path');
163
+ assert.deepEqual(f.display.chatContainer.children, canonical, 'compact-off keeps canonical identity and order');
164
+ assert.equal(native.text, stripAnsi(canonical.flatMap(row => row.render(100)).join('\n')), 'compact-off matches the complete native rendering');
165
+ } finally { f.dispose(); }
166
+ }
167
+
168
+ {
169
+ const f = fixture();
170
+ try {
171
+ f.add({ role: 'custom', customType: 'ddd', display: true, content: 'DDD_NOTICE' });
172
+ const { rows } = f.start();
173
+ const replacement = rows.find(row => row.render(100).some(line => stripAnsi(line).includes('DDD · DDD_NOTICE')));
174
+ assert.equal(replacement.constructor.name, 'WorkChild', 'DDD remains indented within its work section');
175
+ assert.ok(replacement.children[0] instanceof tui.Container, 'DDD replacement retains a host wrapper');
176
+ assert.ok(replacement.children[0].children[0] instanceof tui.Spacer, 'DDD wrapper restores its native internal leading gap');
177
+ assert.ok(!(rows[rows.indexOf(replacement) - 1] instanceof tui.Spacer), 'DDD receives no extra outside gap');
178
+ const pane = replacement.children[0].children.at(-1);
179
+ pane.open = true;
180
+ const expanded = replacement.render(100).map(stripAnsi);
181
+ assert.match(expanded[2], /^ DDD_NOTICE/, 'DDD body follows its header and keeps the work and content insets');
182
+ assert.equal(expanded.length, 3, 'DDD retains only its native outer gap; sole content stays visible');
183
+ pane.open = false;
184
+ assert.equal(replacement.render(100).length, 2, 'collapsed DDD keeps only the native gap and summary');
185
+
186
+ } finally { f.dispose(); }
187
+ }
188
+
189
+ {
190
+ const f = fixture();
191
+ try {
192
+ const source = 'DDD reminder.\n\nFirst paragraph.\n\nSecond paragraph.';
193
+ const recorded = f.add({ role: 'custom', customType: 'ddd', display: true, content: source }).at(-1);
194
+ const { rows } = f.start();
195
+ const replacement = rows.find(row => row.render(100).some(line => stripAnsi(line).includes('DDD · DDD reminder.')));
196
+ const pane = replacement.children[0].children.at(-1); pane.open = true;
197
+ const compact = replacement.render(100).map(stripAnsi);
198
+ assert.equal(compact.filter(line => line.includes('DDD reminder.')).length, 1, 'exact DDD opening summary appears only in its header');
199
+ assert.match(compact[2], /First paragraph/);
200
+ assert.equal(compact[3].trim(), '', 'recorded paragraph spacing stays intact');
201
+ assert.match(compact[4], /Second paragraph/);
202
+ assert.equal(recorded.message.content, source, 'DDD source is not rewritten');
203
+ f.mode.setEnabled(false);
204
+ assert.match(f.paint().text, /DDD reminder\./, 'native mode retains the original DDD text');
205
+ } finally { f.dispose(); }
206
+ }
207
+
208
+ console.log('Work-strip native spacer ownership, internal gaps, hidden rows, trailing gaps and fallback passed');
@@ -0,0 +1,236 @@
1
+ import assert from 'node:assert/strict';
2
+ import { loadSource } from './test-runtime.mjs';
3
+ const { monitorWorkStripSubagents } = await loadSource('./work-strip-subagents.ts');
4
+
5
+ const nativeSetTimeout = globalThis.setTimeout, nativeClearTimeout = globalThis.clearTimeout;
6
+ let now = 0;
7
+ const timers = new Map();
8
+ globalThis.setTimeout = (fn, delay = 0) => {
9
+ const timer = { unref() {} };
10
+ timers.set(timer, { fn, at: now + delay }); return timer;
11
+ };
12
+ globalThis.clearTimeout = timer => timers.delete(timer);
13
+ const tick = milliseconds => {
14
+ const end = now + milliseconds;
15
+ for (;;) {
16
+ const next = [...timers].filter(([, timer]) => timer.at <= end).sort((a, b) => a[1].at - b[1].at)[0];
17
+ if (!next) break;
18
+ now = next[1].at; timers.delete(next[0]); next[1].fn();
19
+ }
20
+ now = end;
21
+ };
22
+ const fixture = (names = []) => {
23
+ const bus = new Map(), requests = [], changes = [];
24
+ const tools = names.map(name => ({ name }));
25
+ const events = {
26
+ on(event, fn) { const handlers = bus.get(event) || new Set(); bus.set(event, handlers); handlers.add(fn); return () => handlers.delete(fn); },
27
+ emit(event, data) { for (const fn of [...bus.get(event) || []]) fn(data); },
28
+ };
29
+ events.on('subagents:rpc:v1:request', request => requests.push(request));
30
+ const pi = { events, getAllTools: () => tools };
31
+ let monitor;
32
+ monitor = monitorWorkStripSubagents(pi, () => changes.push(monitor?.current()));
33
+ const reply = (request = requests.at(-1), data = { fleet: { totalActive: 0 } }, overrides = {}) => events.emit(`subagents:rpc:v1:reply:${request.requestId}`, { version: 1, requestId: request.requestId, method: 'status', success: true, data, ...overrides });
34
+ return { monitor, pi, bus, tools, requests, changes, reply };
35
+ };
36
+ const fixtures = [];
37
+ const make = (...args) => { const value = fixture(...args); fixtures.push(value); return value; };
38
+ try {
39
+ const absent = make(['read', 'subagent_supervisor']);
40
+ assert.equal(absent.monitor.hasProvider(), false);
41
+ assert.equal(absent.monitor.current(), 'idle');
42
+ assert.equal(absent.requests.length, 0, 'no provider causes no status traffic');
43
+ absent.tools.push({ name: 'subagent' }); absent.monitor.refresh();
44
+ assert.equal(absent.monitor.hasProvider(), true);
45
+ assert.equal(absent.monitor.current(), 'unknown', 'late tool registration is detected');
46
+ absent.reply(); assert.equal(absent.monitor.current(), 'idle');
47
+
48
+ const known = make(['subagents']);
49
+ assert.equal(known.monitor.current(), 'unknown');
50
+ assert.equal(known.requests.length, 1, 'initial reset asks once');
51
+ assert.deepEqual(known.requests[0].params, {});
52
+ assert.equal(known.requests[0].method, 'status', 'only read-only status RPC is sent');
53
+ tick(1000);
54
+ assert.equal(known.monitor.current(), 'unknown');
55
+ const requestsAfterTimeout = known.requests.length;
56
+ tick(10_000); assert.equal(known.requests.length, requestsAfterTimeout, 'timeout does not start polling');
57
+ known.monitor.refresh(); known.reply(undefined, { fleet: { totalActive: 2 } });
58
+ assert.equal(known.monitor.current(), 'active');
59
+ known.monitor.refresh(); known.reply(); assert.equal(known.monitor.current(), 'idle');
60
+
61
+ for (const data of [{}, { fleet: { totalActive: -1 } }, { fleet: { totalActive: 1.5 } }, { fleet: { totalActive: '0' } }, { fleet: { totalActive: 0 }, asyncSnapshot: {} }]) {
62
+ known.monitor.refresh(); known.reply(undefined, data);
63
+ assert.equal(known.monitor.current(), 'unknown', 'malformed evidence does not permit folding');
64
+ }
65
+ for (const state of ['queued', 'running', 'pending', 'paused', 'blocked', 'future-state']) {
66
+ known.monitor.refresh(); known.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ state }] } });
67
+ assert.equal(known.monitor.current(), 'active', `${state} remains visible`);
68
+ }
69
+ known.monitor.refresh(); known.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ state: 'complete', children: [{ state: 'paused' }] }] } });
70
+ assert.equal(known.monitor.current(), 'active', 'nested paused work remains visible');
71
+ known.monitor.refresh(); known.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: ['complete', 'failed', 'partial', 'stopped', 'rejected'].map(state => ({ state })) } });
72
+ assert.equal(known.monitor.current(), 'idle');
73
+ for (const omitted of [{ runs: 1 }, { children: 1 }, { byteLimitExceeded: true }]) {
74
+ known.monitor.refresh(); known.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [], omitted } });
75
+ assert.equal(known.monitor.current(), 'unknown', 'omitted snapshot state does not prove all work finished');
76
+ }
77
+ known.monitor.refresh(); known.reply(undefined, undefined, { success: false, error: { code: 'no_active_session' } });
78
+ assert.equal(known.monitor.current(), 'unknown', 'provider failure keeps the strip open');
79
+ known.monitor.refresh(); known.reply(undefined, undefined, { version: 2 });
80
+ assert.equal(known.monitor.current(), 'unknown', 'unknown protocol versions fail closed');
81
+
82
+ known.monitor.refresh(); const stale = known.requests.at(-1);
83
+ known.monitor.reset(); const current = known.requests.at(-1);
84
+ assert.notEqual(stale.requestId, current.requestId);
85
+ known.reply(stale, { fleet: { totalActive: 8 } });
86
+ assert.equal(known.monitor.current(), 'unknown', 'reset invalidates old replies');
87
+ known.reply(current); assert.equal(known.monitor.current(), 'idle');
88
+ known.monitor.refresh(); const pending = known.requests.at(-1);
89
+ known.pi.events.emit('subagent:async-started', {});
90
+ assert.equal(known.monitor.current(), 'active', 'launch makes state active immediately');
91
+ known.reply(pending); assert.equal(known.monitor.current(), 'active', 'reply before launch cannot erase new activity');
92
+ const beforeEvents = known.requests.length;
93
+ for (const event of ['subagent:async-complete', 'subagent:child-status', 'subagent:process-terminal']) known.pi.events.emit(event, {});
94
+ assert.equal(known.requests.length, beforeEvents, 'completion refresh waits for event delivery');
95
+ tick(0); assert.equal(known.requests.length, beforeEvents + 1, 'burst events share one deferred status request');
96
+ known.reply(); assert.equal(known.monitor.current(), 'idle');
97
+
98
+ const late = make();
99
+ late.pi.events.emit('subagents:rpc:v1:ready', {});
100
+ assert.equal(late.monitor.hasProvider(), true);
101
+ assert.equal(late.monitor.current(), 'unknown');
102
+ tick(0); assert.equal(late.requests.length, 1, 'provider readiness handles extension load order');
103
+ late.reply(); assert.equal(late.monitor.current(), 'idle');
104
+ const eventOnly = make();
105
+ eventOnly.pi.events.emit('subagent:async-started', {});
106
+ assert.equal(eventOnly.monitor.hasProvider(), true);
107
+ assert.equal(eventOnly.monitor.current(), 'active', 'async events detect a provider without its tools');
108
+ eventOnly.monitor.reset(); assert.equal(eventOnly.monitor.current(), 'unknown');
109
+ eventOnly.reply(); assert.equal(eventOnly.monitor.current(), 'idle');
110
+
111
+ const scoped = make(['subagent']);
112
+ assert.equal(scoped.monitor.statusFor([]), 'idle');
113
+ assert.equal(scoped.monitor.statusFor(['missing']), 'unknown', 'global idle never proves a missing run finished');
114
+ scoped.reply(undefined, { fleet: { totalActive: 1 }, asyncSnapshot: { runs: [
115
+ { id: 'turn-a', state: 'complete' },
116
+ { id: 'turn-b', state: 'running' },
117
+ { id: 'parent', state: 'complete', children: [{ id: 'child-only', state: 'complete' }] },
118
+ ] } });
119
+ assert.equal(scoped.monitor.current(), 'active');
120
+ assert.equal(scoped.monitor.statusFor(['turn-a']), 'idle', 'unrelated active work does not block a completed turn');
121
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'active');
122
+ assert.equal(scoped.monitor.statusFor(['turn-a', 'turn-b']), 'active');
123
+ assert.equal(scoped.monitor.statusFor(['turn-a', 'missing']), 'unknown');
124
+ assert.equal(scoped.monitor.statusFor(['child-only']), 'unknown', 'snapshot step IDs never settle root launches');
125
+ scoped.monitor.refresh(); scoped.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'turn-b', state: 'paused' }] } });
126
+ assert.equal(scoped.monitor.statusFor(['turn-a']), 'idle', 'refresh retains earlier explicit root evidence');
127
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'active');
128
+ scoped.pi.events.emit('subagent:child-status', { runId: 'turn-b', childId: 'step', state: 'complete' });
129
+ scoped.pi.events.emit('subagent:process-terminal', { runId: 'turn-b', state: 'complete' });
130
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'active', 'child and process completion never settle a root');
131
+ scoped.pi.events.emit('subagent:async-complete', { runId: 'turn-b', childId: 'step', state: 'complete' });
132
+ scoped.pi.events.emit('subagent:async-complete', { id: 'other', runId: 'turn-b', state: 'complete' });
133
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'active', 'ambiguous completion identity is ignored');
134
+ scoped.pi.events.emit('subagent:async-complete', { id: 'turn-b', runId: 'turn-b' });
135
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'active', 'completion without outcome does not prove settlement');
136
+ scoped.pi.events.emit('subagent:async-complete', { id: 'turn-b', runId: 'turn-b', state: 'complete' });
137
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'idle');
138
+ tick(0); scoped.reply(undefined, { fleet: { totalActive: 1 }, asyncSnapshot: { runs: [{ id: 'unrelated', state: 'running' }] } });
139
+ assert.equal(scoped.monitor.current(), 'active');
140
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'idle', 'root completion survives later snapshot cleanup');
141
+ scoped.monitor.refresh(); scoped.reply(undefined, { fleet: { totalActive: 1 }, asyncSnapshot: { runs: [{ id: 'turn-b', state: 'running' }] } });
142
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'active', 'a later snapshot with active state keeps the strip open');
143
+ scoped.pi.events.emit('subagent:async-started', { id: 'turn-b' });
144
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'active', 'restart replaces prior terminal evidence');
145
+ for (const payload of [{ state: 'paused', success: true }, { state: 'blocked' }, { success: false, exitCode: 0 }, { interrupted: true, success: false }]) {
146
+ scoped.pi.events.emit('subagent:async-complete', { id: 'turn-b', ...payload });
147
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'active', 'paused or blocked completion stays open');
148
+ }
149
+ scoped.pi.events.emit('subagent:async-complete', { runId: 'turn-b', success: false });
150
+ assert.equal(scoped.monitor.statusFor(['turn-b']), 'idle', 'root completion boolean records a terminal failure');
151
+ scoped.pi.events.emit('subagent:async-complete', { runId: 'event-only-complete', success: true });
152
+ assert.equal(scoped.monitor.statusFor(['event-only-complete']), 'idle', 'validated root event supplies missing snapshot evidence');
153
+ const staleScopedRequest = scoped.requests.at(-1);
154
+ scoped.monitor.reset();
155
+ assert.equal(scoped.monitor.statusFor(['turn-a', 'turn-b', 'event-only-complete']), 'unknown', 'session reset removes all scoped evidence');
156
+ scoped.reply(staleScopedRequest, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'turn-a', state: 'complete' }] } });
157
+ assert.equal(scoped.monitor.statusFor(['turn-a']), 'unknown', 'old session replies cannot repopulate scoped records');
158
+ scoped.reply();
159
+ assert.equal(scoped.monitor.statusFor(['turn-a']), 'unknown', 'empty snapshot never invents root completion');
160
+
161
+ const workflow = make(['subagent']);
162
+ workflow.pi.events.emit('subagent:async-started', { id: 'workflow' });
163
+ workflow.pi.events.emit('subagent:async-started', { id: 'workflow-child', parentWorkflowRunId: 'workflow', workflowKey: 'lane' });
164
+ workflow.pi.events.emit('subagent:async-complete', { id: 'independent', success: true });
165
+ workflow.pi.events.emit('subagent:async-complete', { id: 'workflow', state: 'complete', success: true, results: [{ workflowKey: 'lane', runId: 'workflow-child', state: 'running' }] });
166
+ assert.equal(workflow.monitor.statusFor(['workflow']), 'active', 'dispatch completion keeps its running result child visible');
167
+ assert.equal(workflow.monitor.statusFor(['independent']), 'idle', 'workflow descendants do not block unrelated roots');
168
+ tick(0); workflow.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'workflow', state: 'complete' }] } });
169
+ assert.equal(workflow.monitor.statusFor(['workflow']), 'active', 'a snapshot that omits a known child cannot settle it');
170
+ workflow.monitor.refresh(); workflow.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'workflow', state: 'complete', children: [{ id: 'lane', kind: 'step', state: 'running' }] }] } });
171
+ assert.equal(workflow.monitor.statusFor(['workflow']), 'active', 'snapshot descendants remain checked after root completion');
172
+ assert.equal(workflow.monitor.statusFor(['lane']), 'unknown', 'workflow step keys never become root run IDs');
173
+ workflow.pi.events.emit('subagent:async-complete', { id: 'workflow-child', state: 'complete', success: true });
174
+ assert.equal(workflow.monitor.statusFor(['workflow']), 'idle', 'the linked child completion settles its owning workflow');
175
+ tick(0); workflow.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'workflow', state: 'complete', children: [{ id: 'lane', kind: 'step', state: 'complete' }] }] } });
176
+ assert.equal(workflow.monitor.statusFor(['workflow']), 'idle', 'terminal snapshot descendants preserve completed ownership');
177
+
178
+ workflow.pi.events.emit('subagent:async-started', { id: 'snapshot-workflow' });
179
+ workflow.pi.events.emit('subagent:async-started', { id: 'snapshot-child', parentWorkflowRunId: 'snapshot-workflow', workflowKey: 'snapshot-lane' });
180
+ workflow.pi.events.emit('subagent:async-complete', { id: 'snapshot-workflow', state: 'complete' });
181
+ assert.equal(workflow.monitor.statusFor(['snapshot-workflow']), 'active', 'launch ownership also works when completion has no results');
182
+ tick(0); workflow.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'snapshot-workflow', state: 'complete', children: [{ id: 'snapshot-lane', kind: 'step', state: 'paused' }] }] } });
183
+ assert.equal(workflow.monitor.statusFor(['snapshot-workflow']), 'active', 'a paused child blocks its workflow');
184
+ workflow.monitor.refresh(); workflow.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'snapshot-workflow', state: 'complete', children: [{ id: 'snapshot-lane', kind: 'step', state: 'complete' }] }] } });
185
+ assert.equal(workflow.monitor.statusFor(['snapshot-workflow']), 'idle', 'an explicit child snapshot can prove descendant completion');
186
+
187
+ workflow.pi.events.emit('subagent:async-started', { id: 'nested-root' });
188
+ workflow.pi.events.emit('subagent:async-started', { id: 'nested-child', parentWorkflowRunId: 'nested-root' });
189
+ workflow.pi.events.emit('subagent:async-started', { id: 'grandchild', parentWorkflowRunId: 'nested-child' });
190
+ workflow.pi.events.emit('subagent:async-complete', { id: 'nested-root', state: 'complete' });
191
+ workflow.pi.events.emit('subagent:async-complete', { id: 'nested-child', state: 'complete' });
192
+ assert.equal(workflow.monitor.statusFor(['nested-root']), 'active', 'a child cannot settle its running descendants');
193
+ workflow.pi.events.emit('subagent:async-complete', { id: 'grandchild', state: 'complete' });
194
+ assert.equal(workflow.monitor.statusFor(['nested-root']), 'idle', 'nested completion propagates to every owning ancestor');
195
+
196
+ workflow.pi.events.emit('subagent:async-complete', { id: 'results-only', state: 'complete', results: [{ runId: 'results-only-child', state: 'running' }] });
197
+ assert.equal(workflow.monitor.statusFor(['results-only']), 'active', 'running result references work without a launch event');
198
+ workflow.pi.events.emit('subagent:async-complete', { id: 'results-only-child', state: 'complete' });
199
+ assert.equal(workflow.monitor.statusFor(['results-only']), 'idle');
200
+ workflow.pi.events.emit('subagent:async-complete', { id: 'anonymous-results', state: 'complete', results: [{ state: 'running' }] });
201
+ assert.equal(workflow.monitor.statusFor(['anonymous-results']), 'active');
202
+ tick(0); workflow.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'anonymous-results', state: 'complete' }] } });
203
+ assert.equal(workflow.monitor.statusFor(['anonymous-results']), 'active', 'absent anonymous descendants also remain unresolved');
204
+ workflow.monitor.refresh(); workflow.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'anonymous-results', state: 'complete', children: [{ id: 'reported-child', state: 'complete' }] }] } });
205
+ assert.equal(workflow.monitor.statusFor(['anonymous-results']), 'idle', 'a full terminal descendant snapshot resolves an anonymous result');
206
+
207
+ workflow.pi.events.emit('subagent:async-complete', { id: 'key-only-results', state: 'complete', results: [{ workflowKey: 'key-only-lane', state: 'running' }] });
208
+ tick(0); workflow.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'key-only-results', state: 'complete', children: [{ id: 'key-only-lane', state: 'complete' }] }] } });
209
+ assert.equal(workflow.monitor.statusFor(['key-only-results']), 'idle', 'matching workflow keys resolve results without a run ID');
210
+ workflow.pi.events.emit('subagent:async-complete', { id: 'anonymous-nested', state: 'complete', results: [{ state: 'complete', children: [{ state: 'running' }] }] });
211
+ assert.equal(workflow.monitor.statusFor(['anonymous-nested']), 'active', 'anonymous nested completion results retain running descendants');
212
+ tick(0); workflow.reply(undefined, { fleet: { totalActive: 0 }, asyncSnapshot: { runs: [{ id: 'self-step', state: 'complete', children: [{ id: 'self-step', kind: 'step', state: 'complete' }] }] } });
213
+ assert.equal(workflow.monitor.statusFor(['self-step']), 'idle', 'a self-named step does not create a dependency cycle');
214
+
215
+ // A provider may answer synchronously on the process-local bus.
216
+ const synchronous = make(['subagent']);
217
+ synchronous.pi.events.on('subagents:rpc:v1:request', request => synchronous.reply(request));
218
+ synchronous.monitor.refresh(); assert.equal(synchronous.monitor.current(), 'idle');
219
+ tick(1000); assert.equal(synchronous.monitor.current(), 'idle');
220
+ synchronous.monitor.refresh(); const last = synchronous.requests.at(-1);
221
+ const traffic = synchronous.requests.length;
222
+ synchronous.pi.events.emit('subagent:child-status', {});
223
+ const beforeDispose = synchronous.changes.length;
224
+ synchronous.monitor.dispose(); synchronous.monitor.dispose();
225
+ synchronous.reply(last, { fleet: { totalActive: 9 } });
226
+ synchronous.pi.events.emit('subagent:async-started', {});
227
+ tick(2000);
228
+ assert.equal(synchronous.requests.length, traffic);
229
+ assert.equal(synchronous.changes.length, beforeDispose, 'dispose cancels timers and callbacks');
230
+ assert.equal([...synchronous.bus.entries()].filter(([key]) => key.startsWith('subagents:rpc:v1:reply:')).reduce((sum, [, handlers]) => sum + handlers.size, 0), 0);
231
+ console.log('work strip subagents: scoped root runs, provider load order, read-only status, deferred events, timeout, stale replies, snapshots and disposal passed');
232
+ } finally {
233
+ fixtures.forEach(({ monitor }) => monitor.dispose());
234
+ assert.equal(timers.size, 0, 'all monitor timers are released');
235
+ globalThis.setTimeout = nativeSetTimeout; globalThis.clearTimeout = nativeClearTimeout;
236
+ }