-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagenticoding.test.ts
More file actions
3618 lines (3113 loc) · 129 KB
/
agenticoding.test.ts
File metadata and controls
3618 lines (3113 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import test, { after } from "node:test";
import assert from "node:assert/strict";
import type { Theme } from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";
import { registerHandoffCommand } from "./handoff/command.js";
import { registerHandoffTool } from "./handoff/tool.js";
import { registerHandoffCompaction } from "./handoff/compact.js";
import { buildNudge, registerWatchdog } from "./watchdog.js";
import { createState, resetState } from "./state.js";
import {
buildChildToolNames,
createChildTools,
executeSpawn,
registerSpawnTool,
} from "./spawn/index.js";
import { renderSpawnResult, flushSpawnFrameScheduler, resetSpawnFrameScheduler } from "./spawn/renderer.js";
import { registerNotebookRehydration } from "./notebook/rehydration.js";
import { clearActiveNotebookTopic, setActiveNotebookTopic } from "./notebook/topic.js";
import { registerNotebookTopicTool } from "./notebook/topic-tool.js";
import { saveNotebookPage, resetNotebookWriteLock } from "./notebook/store.js";
import { createNotebookToolDefinitions } from "./notebook/tools.js";
import registerAgenticoding from "./index.js";
import { CONTEXT_PRIMER } from "./system-prompt.js";
import { STATUS_KEY_HANDOFF, STATUS_KEY_TOPIC, WIDGET_KEY_WARNING, updateIndicators } from "./tui.js";
// Safety net: reset module-level mutable state after all tests.
// Individual tests should also call reset*() at the start for explicit isolation.
after(() => {
resetNotebookWriteLock();
resetSpawnFrameScheduler();
});
type Handler = (args: any, ctx: any) => any;
const theme = {
fg: (_name: string, text: string) => text,
bold: (text: string) => text,
} as unknown as Theme;
const ansiTheme = {
fg: (_name: string, text: string) => `\u001b[38;5;245m${text}\u001b[39m`,
bg: (_name: string, text: string) => `\u001b[48;5;236m${text}\u001b[49m`,
bold: (text: string) => text,
} as unknown as Theme;
function createRenderContext(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
expanded: false,
showImages: true,
toolCallId: "tool-call-1",
lastComponent: undefined,
invalidate: () => {},
...overrides,
};
}
function createSession(messages: any[]) {
return {
messages,
subscribe: () => () => {},
getToolDefinition: () => undefined,
sessionManager: { getCwd: () => process.cwd() },
abort: async () => {},
} as unknown as import("@earendil-works/pi-coding-agent").AgentSession;
}
function stripAnsi(text: string): string {
return text.replace(/\u001b\[[0-9;]*m/g, "").replace(/\u001b\][^\u0007]*\u0007/g, "");
}
function getRenderedLine(lines: string[], match: (plain: string) => boolean): string {
const line = lines.find(candidate => match(stripAnsi(candidate)));
assert.ok(line);
return line;
}
function getLineContaining(lines: string[], text: string): string {
const line = lines.find(candidate => candidate.includes(text));
assert.ok(line);
return line;
}
function assertShellBackgroundPreserved(line: string): void {
assert.equal(line.includes("\u001b[0m"), false);
assert.match(line, /\u001b\[48;/);
}
function createDeferred() {
let resolve!: () => void;
const promise = new Promise<void>((r) => { resolve = r; });
return { promise, resolve };
}
function createChildSpawnTool(state: any): any {
const pi = new MockPi();
registerSpawnTool(pi as any, state);
return pi.tools.get("spawn");
}
class MockPi {
commands = new Map<string, { description?: string; handler: Handler }>();
tools = new Map<string, any>();
handlers = new Map<string, Handler[]>();
activeTools: string[] = [];
toolSources = new Map<string, string>();
sentUserMessages: Array<{ content: string; options: any }> = [];
appendedEntries: Array<{ customType: string; data: any }> = [];
registerCommand(name: string, definition: { description?: string; handler: Handler }) {
this.commands.set(name, definition);
}
registerTool(definition: any) {
this.tools.set(definition.name, definition);
}
on(event: string, handler: Handler) {
const handlers = this.handlers.get(event) ?? [];
handlers.push(handler);
this.handlers.set(event, handlers);
}
getActiveTools() {
return [...this.activeTools];
}
setActiveTools(tools: string[]) {
this.activeTools = [...tools];
for (const tool of tools) {
if (!this.toolSources.has(tool)) {
this.toolSources.set(tool, "builtin");
}
}
}
setToolSource(name: string, source: string) {
this.toolSources.set(name, source);
}
getAllTools() {
return this.activeTools.map((name) => ({
name,
description: "",
parameters: {},
sourceInfo: {
path: `<${this.toolSources.get(name) ?? "builtin"}:${name}>`,
source: this.toolSources.get(name) ?? "builtin",
scope: "temporary",
origin: "top-level",
},
}));
}
getThinkingLevel() {
return "medium";
}
sendUserMessage(content: string, options?: any) {
this.sentUserMessages.push({ content, options });
}
appendEntry(customType: string, data: any) {
this.appendedEntries.push({ customType, data });
}
}
// ── TUI indicator tests ───────────────────────────────────────────────
function makeTUICtx(
overrides: Partial<{
percent: number | null;
hasUI: boolean;
record: { statuses: Map<string, string | undefined>; widgets: Map<string, string[] | undefined> };
}> = {},
): any {
const record = overrides.record ?? { statuses: new Map(), widgets: new Map() };
const hasUI = overrides.hasUI ?? true;
const percent = overrides.percent !== undefined ? overrides.percent : null;
return {
hasUI,
ui: {
theme: {
fg: (name: string, text: string) => `[${name}:${text}]`,
},
setStatus: (key: string, status: string | undefined) => { record.statuses.set(key, status); },
setWidget: (key: string, content: string[] | undefined) => { record.widgets.set(key, content); },
},
getContextUsage: () => (percent !== null ? { percent } : null),
};
}
test("updateIndicators sets context usage status with correct color tone", () => {
const state = createState();
const record = { statuses: new Map<string, string | undefined>(), widgets: new Map<string, string[] | undefined>() };
const ctx = makeTUICtx({ percent: 42, record });
updateIndicators(ctx, state);
const s = record.statuses.get("agenticoding-ctx");
assert.ok(s?.includes("[accent:42%]"), "42% should use accent tone");
assert.equal(record.widgets.get("agenticoding-warning"), undefined, "42% is below 70 — no warning widget");
});
test("updateIndicators uses error tone at 70%+ context", () => {
const state = createState();
const record = { statuses: new Map<string, string | undefined>(), widgets: new Map<string, string[] | undefined>() };
const ctx = makeTUICtx({ percent: 85, record });
updateIndicators(ctx, state);
const s = record.statuses.get("agenticoding-ctx");
assert.ok(s?.includes("[error:85%]"), "85% should use error tone");
const w = record.widgets.get("agenticoding-warning");
assert.ok(w?.[0]?.includes("85%"), "warning widget shown at 85%");
});
test("updateIndicators uses warning tone at 50-69% context", () => {
const state = createState();
const record = { statuses: new Map<string, string | undefined>(), widgets: new Map<string, string[] | undefined>() };
const ctx = makeTUICtx({ percent: 55, record });
updateIndicators(ctx, state);
const s = record.statuses.get("agenticoding-ctx");
assert.ok(s?.includes("[warning:55%]"), "55% should use warning tone");
});
test("updateIndicators uses accent tone at 30-49% context", () => {
const state = createState();
const record = { statuses: new Map<string, string | undefined>(), widgets: new Map<string, string[] | undefined>() };
const ctx = makeTUICtx({ percent: 30, record });
updateIndicators(ctx, state);
const s = record.statuses.get("agenticoding-ctx");
assert.ok(s?.includes("[accent:30%]"), "30% should use accent tone");
});
test("updateIndicators handles null context usage", () => {
const state = createState();
const record = { statuses: new Map<string, string | undefined>(), widgets: new Map<string, string[] | undefined>() };
const ctx = makeTUICtx({ percent: null, record });
updateIndicators(ctx, state);
const s = record.statuses.get("agenticoding-ctx");
assert.ok(s?.includes("--%"), "null usage shows --%");
});
test("updateIndicators no-ops when ctx.hasUI is false", () => {
const state = createState();
const record = { statuses: new Map<string, string | undefined>(), widgets: new Map<string, string[] | undefined>() };
const ctx = makeTUICtx({ hasUI: false, record });
updateIndicators(ctx, state);
assert.equal(record.statuses.size, 0, "no-op should not call any setStatus");
assert.equal(record.widgets.size, 0, "no-op should not call any setWidget");
});
test("updateIndicators shows notebook page count in status", () => {
const state = createState();
state.notebookPages.set("entry-1", "first entry");
state.notebookPages.set("entry-2", "second entry");
const record = { statuses: new Map<string, string | undefined>(), widgets: new Map<string, string[] | undefined>() };
const ctx = makeTUICtx({ percent: null, record });
updateIndicators(ctx, state);
const s = record.statuses.get("agenticoding-notebook");
assert.ok(s?.includes("2"), "notebook page count should be 2");
});
test("updateIndicators shows active notebook topic when set", () => {
const state = createState();
state.activeNotebookTopic = "oauth";
const record = { statuses: new Map<string, string | undefined>(), widgets: new Map<string, string[] | undefined>() };
const ctx = makeTUICtx({ percent: 30, record });
updateIndicators(ctx, state);
assert.equal(record.statuses.get(STATUS_KEY_TOPIC), "🧭 oauth");
});
test("updateIndicators hides widget below 70% context", () => {
const state = createState();
const record = { statuses: new Map<string, string | undefined>(), widgets: new Map<string, string[] | undefined>() };
// Pre-set a widget to verify it gets cleared
record.widgets.set("agenticoding-warning", ["existing"]);
const ctx = makeTUICtx({ percent: 30, record });
updateIndicators(ctx, state);
assert.equal(record.widgets.get("agenticoding-warning"), undefined, "warning widget should be cleared below 70%");
});
// ── Handoff tests ─────────────────────────────────────────────────────
test("/handoff sends the direction back through the LLM without opening the editor", async () => {
const pi = new MockPi();
const state = createState();
registerHandoffCommand(pi as any, state);
await pi.commands.get("handoff")!.handler("implement auth", {
hasUI: true,
isIdle: () => true,
ui: { notify: (_message: string) => {} },
});
assert.deepEqual(state.pendingRequestedHandoff, {
direction: "implement auth",
enforcementAttempts: 0,
toolCalled: false,
});
assert.deepEqual(pi.sentUserMessages, [
{
content:
"Handoff direction: implement auth\n\nPrepare a handoff in the current session. First, save any durable reusable knowledge to the notebook: findings worth keeping, constraints discovered, decisions made, or other grounding future contexts will need. Then draft a concise but sufficiently detailed handoff brief capturing only the remaining situational context: current state, blockers, unresolved questions, failed paths worth avoiding, and next steps. The next context will read the notebook on demand, so do not duplicate notebook content in the brief. Use any structure that makes the next work unambiguous. Reference notebook pages by name when relevant.",
options: undefined,
},
]);
});
test("/handoff requires a direction", async () => {
const pi = new MockPi();
const state = createState();
registerHandoffCommand(pi as any, state);
const notifications: string[] = [];
await pi.commands.get("handoff")!.handler(" ", {
hasUI: true,
isIdle: () => true,
ui: { notify: (message: string) => notifications.push(message) },
});
assert.deepEqual(notifications, ["Usage: /handoff <direction>"]);
assert.deepEqual(pi.sentUserMessages, []);
});
test("handoff tool triggers compaction and resumes with the compacted task", async () => {
const pi = new MockPi();
const state = createState();
state.notebookPages.set("auth-refresh", "sensitive notebook body");
state.pendingRequestedHandoff = { direction: "implement auth", enforcementAttempts: 0, toolCalled: false };
registerHandoffTool(pi as any, state);
let compactOptions: any;
const result = await pi.tools.get("handoff").execute(
"1",
{ task: "Goal: continue auth-refresh" },
undefined,
undefined,
{
compact: (options: any) => {
compactOptions = options;
},
},
);
assert.equal(state.pendingHandoff?.source, "tool");
assert.match(state.pendingHandoff?.task ?? "", /## Handoff — Continue Previous Work/);
assert.match(state.pendingHandoff?.task ?? "", /Notebook pages hold durable grounding knowledge/);
assert.match(state.pendingHandoff?.task ?? "", /distilled next task and immediate situational context/);
assert.match(state.pendingHandoff?.task ?? "", /Goal: continue auth-refresh/);
assert.doesNotMatch(state.pendingHandoff?.task ?? "", /sensitive notebook body/);
assert.equal(state.pendingRequestedHandoff?.toolCalled, true);
assert.equal(typeof compactOptions?.onComplete, "function");
assert.equal(result.content[0].text, "Handoff started.");
assert.equal(result.terminate, true);
compactOptions.onComplete({});
assert.deepEqual(pi.sentUserMessages, [{ content: "Proceed.", options: undefined }]);
});
test("handoff compaction replaces old context with the queued task", async () => {
const pi = new MockPi();
const state = createState();
state.pendingHandoff = { task: "Goal: continue", source: "tool" };
state.pendingRequestedHandoff = { direction: "implement auth", enforcementAttempts: 1, toolCalled: true };
state.activeNotebookTopic = "oauth";
state.activeNotebookTopicSource = "human";
registerHandoffCompaction(pi as any, state);
const [handler] = pi.handlers.get("session_before_compact")!;
const result = await handler(
{
preparation: { tokensBefore: 123 },
branchEntries: [{ id: "leaf-1" }],
},
{},
);
assert.equal(state.pendingHandoff, null);
assert.equal(state.pendingRequestedHandoff, null);
assert.equal(state.activeNotebookTopic, null);
assert.equal(state.activeNotebookTopicSource, null);
assert.equal(result.compaction.summary, "Goal: continue");
assert.equal(result.compaction.tokensBefore, 123);
assert.equal(result.compaction.firstKeptEntryId, "leaf-1-handoff-cut");
assert.deepEqual(result.compaction.details, { handoff: true, task: "Goal: continue" });
});
test("/handoff sets the handoff status indicator", async () => {
const pi = new MockPi();
const state = createState();
registerHandoffCommand(pi as any, state);
const statuses = new Map<string, string | undefined>();
await pi.commands.get("handoff")!.handler("implement auth", {
hasUI: true,
isIdle: () => true,
ui: {
theme: { fg: (_name: string, text: string) => text },
notify: () => {},
setStatus: (key: string, value: string | undefined) => { statuses.set(key, value); },
},
});
assert.equal(statuses.get(STATUS_KEY_HANDOFF), "🤝 Handoff in progress");
});
test("handoff compaction clears the handoff status indicator", async () => {
const pi = new MockPi();
const state = createState();
state.pendingHandoff = { task: "Goal: continue", source: "tool" };
registerHandoffCompaction(pi as any, state);
const statuses = new Map<string, string | undefined>();
const [handler] = pi.handlers.get("session_before_compact")!;
await handler(
{ preparation: { tokensBefore: 1 }, branchEntries: [{ id: "leaf-1" }] },
{ hasUI: true, ui: { setStatus: (key: string, value: string | undefined) => { statuses.set(key, value); } } },
);
assert.equal(statuses.get(STATUS_KEY_HANDOFF), undefined);
});
test("handoff compaction error clears pending state and status", async () => {
const pi = new MockPi();
const state = createState();
state.pendingRequestedHandoff = { direction: "implement auth", enforcementAttempts: 0, toolCalled: false };
registerHandoffTool(pi as any, state);
let compactOptions: any;
const statuses = new Map<string, string | undefined>();
await pi.tools.get("handoff").execute(
"1",
{ task: "Goal: continue" },
undefined,
undefined,
{
hasUI: true,
ui: { setStatus: (key: string, value: string | undefined) => { statuses.set(key, value); } },
compact: (options: any) => { compactOptions = options; },
},
);
compactOptions.onError({});
assert.equal(state.pendingHandoff, null);
assert.equal(state.pendingRequestedHandoff?.toolCalled, false);
assert.equal(statuses.get(STATUS_KEY_HANDOFF), undefined);
});
test("turn_end fallback clears stale requested handoff status", async () => {
const pi = new MockPi();
registerAgenticoding(pi as any);
const statuses = new Map<string, string | undefined>();
await pi.commands.get("handoff")!.handler("implement auth", {
hasUI: true,
isIdle: () => true,
ui: {
theme: { fg: (_name: string, text: string) => text },
notify: () => {},
setStatus: (key: string, value: string | undefined) => { statuses.set(key, value); },
},
});
const [turnEnd] = pi.handlers.get("turn_end")!;
await turnEnd({}, {
hasUI: true,
ui: {
theme: { fg: (_name: string, text: string) => text },
setStatus: (key: string, value: string | undefined) => { statuses.set(key, value); },
setWidget: () => {},
},
getContextUsage: () => null,
});
assert.equal(statuses.get(STATUS_KEY_HANDOFF), undefined);
});
test("session_start new clears stale handoff status and warning widget", async () => {
const pi = new MockPi();
registerAgenticoding(pi as any);
const statuses = new Map<string, string | undefined>([[STATUS_KEY_HANDOFF, "stale"]]);
const widgets = new Map<string, string[] | undefined>([[WIDGET_KEY_WARNING, ["stale"]]]);
const sessionStartHandlers = pi.handlers.get("session_start")!;
const ctx = {
hasUI: true,
ui: {
theme: { fg: (_name: string, text: string) => text },
setStatus: (key: string, value: string | undefined) => { statuses.set(key, value); },
setWidget: (key: string, value: string[] | undefined) => { widgets.set(key, value); },
},
sessionManager: { getBranch: () => [] },
getContextUsage: () => null,
};
for (const sessionStart of sessionStartHandlers) {
await sessionStart({ reason: "new" }, ctx);
}
assert.equal(statuses.get(STATUS_KEY_HANDOFF), undefined);
assert.equal(widgets.get(WIDGET_KEY_WARNING), undefined);
});
test("watchdog records context usage without user notifications", async () => {
const pi = new MockPi();
const state = createState();
registerWatchdog(pi as any, state);
const [handler] = pi.handlers.get("agent_end")!;
const notifications: string[] = [];
await handler(
{},
{
hasUI: true,
ui: { notify: (message: string) => notifications.push(message) },
getContextUsage: () => ({ percent: 70 }),
},
);
assert.equal(state.lastContextPercent, 70);
assert.deepEqual(notifications, []);
});
test("context injects watchdog reminder before each LLM call", async () => {
const pi = new MockPi();
registerAgenticoding(pi as any);
const [handler] = pi.handlers.get("context")!;
await pi.commands.get("notebook")!.handler("oauth", { hasUI: false, getContextUsage: () => null });
const result = await handler(
{ messages: [{ role: "user", content: "hi", timestamp: 1 }] },
{
getContextUsage: () => ({ percent: 70 }),
},
);
assert.equal(result.messages.length, 2);
assert.deepEqual(result.messages[0], { role: "user", content: "hi", timestamp: 1 });
assert.equal(result.messages[1].role, "custom");
assert.equal(result.messages[1].customType, "agenticoding-watchdog");
assert.equal(result.messages[1].display, false);
assert.match(result.messages[1].content, /Context at 70%/);
assert.match(result.messages[1].content, /Active notebook topic: oauth/);
assert.match(result.messages[1].content, /spawn it instead of polluting the parent context/i);
assert.doesNotMatch(result.messages[1].content, /If you're mid-job and still clear|consider a handoff and draft a clear brief for what comes next/i);
});
test("context injects a boundary nudge below 30% after an explicit topic change", async () => {
const pi = new MockPi();
registerAgenticoding(pi as any);
const [handler] = pi.handlers.get("context")!;
await pi.commands.get("notebook")!.handler("oauth", { hasUI: false, getContextUsage: () => null });
await pi.commands.get("notebook")!.handler("billing", { hasUI: false, getContextUsage: () => null });
const result = await handler(
{ messages: [{ role: "user", content: "hi", timestamp: 1 }] },
{ getContextUsage: () => ({ percent: 20 }) },
);
assert.equal(result.messages[1].display, false);
assert.match(result.messages[1].content, /Notebook topic changed from oauth to billing/);
});
test("context injects a no-topic nudge when context is high", async () => {
const pi = new MockPi();
registerAgenticoding(pi as any);
const [handler] = pi.handlers.get("context")!;
const result = await handler(
{ messages: [{ role: "user", content: "hi", timestamp: 1 }] },
{ getContextUsage: () => ({ percent: 70 }) },
);
assert.equal(result.messages.length, 2);
assert.equal(result.messages[1].role, "custom");
assert.equal(result.messages[1].customType, "agenticoding-watchdog");
assert.equal(result.messages[1].display, false);
assert.match(result.messages[1].content, /No active notebook topic is set/);
assert.match(result.messages[1].content, /Assign a fresh topic in the next clean context after handoff/i);
});
test("context consumes a boundary hint after the first injected nudge", async () => {
const pi = new MockPi();
registerAgenticoding(pi as any);
const [handler] = pi.handlers.get("context")!;
await pi.commands.get("notebook")!.handler("oauth", { hasUI: false, getContextUsage: () => null });
await pi.commands.get("notebook")!.handler("billing", { hasUI: false, getContextUsage: () => null });
const first = await handler(
{ messages: [{ role: "user", content: "hi", timestamp: 1 }] },
{ getContextUsage: () => ({ percent: 20 }) },
);
assert.match(first.messages[1].content, /Notebook topic changed from oauth to billing/);
const second = await handler(
{ messages: [{ role: "user", content: "hi", timestamp: 2 }] },
{ getContextUsage: () => ({ percent: 20 }) },
);
assert.equal(second, undefined);
});
test("buildNudge handles null percent and boundary hints before topic guidance", () => {
const boundary = buildNudge(
{
activeNotebookTopic: "oauth",
pendingTopicBoundaryHint: { from: "oauth", to: "billing", source: "human" },
},
null,
);
assert.match(boundary, /Notebook topic changed from oauth to billing/);
assert.doesNotMatch(boundary, /Active notebook topic: oauth/);
const noTopic = buildNudge({ activeNotebookTopic: null, pendingTopicBoundaryHint: null }, null);
assert.match(noTopic, /Topic-aware context reminder/);
assert.match(noTopic, /No active notebook topic is set/);
});
test("watchdog stays advisory when a requested handoff is not completed", async () => {
const pi = new MockPi();
const state = createState();
state.pendingRequestedHandoff = { direction: "implement auth", enforcementAttempts: 0, toolCalled: false };
registerWatchdog(pi as any, state);
const [handler] = pi.handlers.get("agent_end")!;
const notifications: string[] = [];
await handler(
{},
{
hasUI: true,
ui: {
notify: (message: string) => notifications.push(message),
setStatus: () => {},
},
getContextUsage: () => ({ percent: 20 }),
},
);
assert.equal(state.pendingRequestedHandoff, null);
assert.deepEqual(notifications, []);
assert.deepEqual(pi.sentUserMessages, []);
});
test("collapsed nested spawn render shows preview and stats", () => {
const state = createState();
const childSpawnTool = createChildSpawnTool(state);
const session = createSession([
{ role: "assistant", content: [{ type: "text", text: "one\ntwo\nthree\nfour\nfive\nsix\nseven" }] },
]);
state.childSessions.set("tool-call-1", session);
const component = childSpawnTool.renderResult(
{
content: [{ type: "text", text: "ignored" }],
details: {
model: "mock-model",
thinking: "medium",
truncated: true,
stats: { inputTokens: 12, outputTokens: 34, turns: 2, cost: 0.125 },
},
},
{ expanded: false },
theme,
createRenderContext(),
) as any;
const lines = component.render(120);
assert.ok(lines.some((l: string) => l.includes("mock-model • medium")));
assert.ok(lines.some((l: string) => l.includes("one")));
assert.ok(lines.some((l: string) => l.includes("five")));
assert.ok(lines.some((l: string) => l.includes("... 2 more lines")));
assert.ok(lines.some((l: string) => l.includes("tok 12/34")));
assert.ok(lines.some((l: string) => l.includes("trunc")));
});
test("collapsed nested spawn render keeps all text blocks from the last assistant message", () => {
const state = createState();
const childSpawnTool = createChildSpawnTool(state);
const session = createSession([
{ role: "assistant", content: [{ type: "text", text: "first" }, { type: "text", text: "second" }] },
]);
state.childSessions.set("tool-call-1", session);
const component = childSpawnTool.renderResult(
{
content: [{ type: "text", text: "ignored" }],
details: { model: "mock-model", thinking: "medium", truncated: false },
},
{ expanded: false },
theme,
createRenderContext(),
) as any;
const lines = component.render(120);
assert.ok(lines.some((l: string) => l.includes("first")));
assert.ok(lines.some((l: string) => l.includes("second")));
});
test("collapsed nested spawn truncation preserves shell background across preview and stats lines", () => {
const state = createState();
const childSpawnTool = createChildSpawnTool(state);
const session = createSession([
{ role: "assistant", content: [{ type: "text", text: "Research the nudge on toggle off TODO from the readonly mode plan." }] },
]);
state.childSessions.set("tool-call-1", session);
const component = childSpawnTool.renderResult(
{
content: [{ type: "text", text: "ignored" }],
details: {
model: "mock-model",
thinking: "medium",
truncated: true,
stats: { inputTokens: 12, outputTokens: 34, turns: 2, cost: 0.125 },
},
},
{ expanded: false },
ansiTheme,
createRenderContext(),
) as any;
const lines = component.render(24);
const previewLine = getRenderedLine(lines, plain => plain.includes("Research"));
const statsLine = getRenderedLine(lines, plain => plain.includes("tok 12/34"));
assertShellBackgroundPreserved(previewLine);
assertShellBackgroundPreserved(statsLine);
assert.match(stripAnsi(statsLine), /tok 12\/34/);
});
test("collapsed nested spawn keeps truncated stats line calm", () => {
const markerTheme = {
fg: (name: string, text: string) => `<${name}>${text}</${name}>`,
bg: (_name: string, text: string) => text,
bold: (text: string) => text,
} as unknown as Theme;
const state = createState();
const childSpawnTool = createChildSpawnTool(state);
const session = createSession([
{ role: "assistant", content: [{ type: "text", text: "short preview" }] },
]);
state.childSessions.set("tool-call-1", session);
const component = childSpawnTool.renderResult(
{
content: [{ type: "text", text: "ignored" }],
details: {
model: "mock-model",
thinking: "medium",
truncated: true,
stats: { inputTokens: 12, outputTokens: 34, turns: 2, cost: 0.125 },
},
},
{ expanded: false },
markerTheme,
createRenderContext(),
) as any;
const lines = component.render(120);
const statsLine = getLineContaining(lines, "tok 12/34");
assert.match(statsLine, /<dim>.*tok 12\/34.*trunc.*<\/dim>/);
assert.equal(statsLine.includes("<warning>"), false);
});
test("nested spawn render is safe without details", () => {
const state = createState();
const childSpawnTool = createChildSpawnTool(state);
const session = createSession([
{ role: "assistant", content: [{ type: "text", text: "hello" }] },
]);
state.childSessions.set("tool-call-1", session);
const component = childSpawnTool.renderResult(
{ content: [{ type: "text", text: "ignored" }] },
{ expanded: false },
theme,
createRenderContext(),
) as any;
const lines = component.render(120);
assert.ok(lines.some((l: string) => l.includes("hello")));
});
test("expanded nested spawn header stays within width after indent", () => {
const state = createState();
const childSpawnTool = createChildSpawnTool(state);
const session = createSession([
{ role: "assistant", content: [{ type: "text", text: "hello" }] },
]);
state.childSessions.set("tool-call-1", session);
const component = childSpawnTool.renderResult(
{
content: [{ type: "text", text: "ignored" }],
details: { model: "model-name", thinking: "medium", truncated: false },
},
{ expanded: true },
theme,
createRenderContext({ expanded: true }),
) as any;
const lines = component.render(24);
const headerLine = lines.find((line: string) => line.includes("model-name")) ?? "";
assert.ok(headerLine.startsWith(" "));
assert.ok(stripAnsi(headerLine).length <= 24);
});
test("nested spawn clears cached render when showImages changes", () => {
const state = createState();
const childSpawnTool = createChildSpawnTool(state);
const session = createSession([
{ role: "assistant", content: [{ type: "text", text: "hello" }, { type: "image", data: "iVBOR", mimeType: "image/png" }] },
]);
state.childSessions.set("tool-call-1", session);
const component = childSpawnTool.renderResult(
{
content: [{ type: "text", text: "ignored" }],
details: { model: "mock-model", thinking: "medium", truncated: false },
},
{ expanded: true },
theme,
createRenderContext({ expanded: true, showImages: true }),
) as any;
const linesWithImages = component.render(120);
const sameComponent = childSpawnTool.renderResult(
{
content: [{ type: "text", text: "ignored" }],
details: { model: "mock-model", thinking: "medium", truncated: false },
},
{ expanded: true },
theme,
createRenderContext({ expanded: true, showImages: false, lastComponent: component }),
) as any;
const linesWithoutImages = sameComponent.render(120);
assert.equal(sameComponent, component);
// Both render calls produce valid output — cache invalidation is verified
// implicitly because the second output reflects the showImages change
// rather than returning stale cached content from the first call.
assert.ok(Array.isArray(linesWithImages));
assert.ok(Array.isArray(linesWithoutImages));
});
test("nested spawn rerenders when stats become unavailable", () => {
const state = createState();
const childSpawnTool = createChildSpawnTool(state);
const session = createSession([
{ role: "assistant", content: [{ type: "text", text: "hello" }] },
]);
state.childSessions.set("tool-call-1", session);
const component = childSpawnTool.renderResult(
{
content: [{ type: "text", text: "ignored" }],
details: { model: "mock-model", thinking: "medium", truncated: false },
},
{ expanded: false },
theme,
createRenderContext(),
) as any;
const before = component.render(120);
assert.equal(before.some((l: string) => l.includes("stats unavailable")), false);
const sameComponent = childSpawnTool.renderResult(
{
content: [{ type: "text", text: "ignored" }],
details: { model: "mock-model", thinking: "medium", truncated: false, outcome: "success", statsUnavailable: true },
},
{ expanded: false },
theme,
createRenderContext({ lastComponent: component }),
) as any;
const after = sameComponent.render(120);
assert.equal(sameComponent, component);
assert.ok(after.some((l: string) => l.includes("stats unavailable")));
assert.equal(after.some((l: string) => l.includes("initializing")), false);
});
test("spawn execute propagates only executable parent tools to child session", async () => {
const pi = new MockPi();
pi.setActiveTools(["read", "bash", "spawn", "handoff", "future_tool"]);
pi.setToolSource("future_tool", "project");
const state = createState();
let seenConfig: any;
const mockFactory = async (config: any) => {
seenConfig = config;
const session = {
messages: [] as any[],
prompt: async () => {
session.messages = [{ role: "assistant", content: [{ type: "text", text: "child result" }] }];
},
abort: async () => {},
getSessionStats: () => undefined,
};
return { session: session as any };
};
registerSpawnTool(pi as any, state, mockFactory as any);
await pi.tools.get("spawn").execute(
"spawn-1",
{ prompt: "Do the task", thinking: "high" },
undefined,
undefined,
{ model: { id: "mock-model" }, cwd: "/tmp" },
);
assert.equal(seenConfig.model.id, "mock-model");
assert.equal(seenConfig.thinkingLevel, "high");
assert.equal(seenConfig.cwd, "/tmp");
assert.equal(seenConfig.tools.includes("read"), true);
assert.equal(seenConfig.tools.includes("bash"), true);
assert.equal(seenConfig.tools.includes("future_tool"), false);
assert.equal(seenConfig.tools.includes("handoff"), false);
assert.equal(seenConfig.tools.includes("spawn"), false);
});
test("spawn execute builds prompt with notebook pages and task", async () => {
const pi = new MockPi();
pi.setActiveTools(["read", "bash", "spawn"]);
const state = createState();
state.notebookPages.set("entry-a", "preview line\nfull body");
let seenPrompt = "";
const mockFactory = async (config: any) => {
const session = {
messages: [] as any[],
prompt: async (prompt: string) => {
seenPrompt = prompt;
session.messages = [{ role: "assistant", content: [{ type: "text", text: "child result" }] }];
},
abort: async () => {},
getSessionStats: () => undefined,
};
return { session: session as any };
};
registerSpawnTool(pi as any, state, mockFactory as any);
await pi.tools.get("spawn").execute(
"spawn-1",
{ prompt: "Do the task" },
undefined,
undefined,
{ model: { id: "mock-model" }, cwd: "/tmp" },
);
// Verify user-facing invariants: task text is included, notebook pages are referenced
assert.match(seenPrompt, /Do the task/);
assert.match(seenPrompt, /entry-a: preview line/);
});
test("spawn renderResult falls back to static text when no live session is stored", () => {
const state = createState();
const pi = new MockPi();
registerSpawnTool(pi as any, state);
const result = pi.tools.get("spawn").renderResult(
{
content: [{ type: "text", text: "fallback output" }],
details: { model: "m", thinking: "low", truncated: false },
},
{ expanded: false },
theme,
createRenderContext(),
) as any;
const lines = result.render(120);
assert.ok(lines.some((l: string) => l.includes("m • low")));
assert.ok(lines.some((l: string) => l.includes("fallback output")));
});
test("spawn renderResult distinguishes aborted and error outcomes", () => {
const state = createState();
const pi = new MockPi();
registerSpawnTool(pi as any, state);
const aborted = pi.tools.get("spawn").renderResult(
{
content: [{ type: "text", text: "stopped" }],
details: { model: "m", thinking: "low", truncated: false, outcome: "aborted" },
},
{ expanded: false },
theme,
createRenderContext(),
) as any;
const error = pi.tools.get("spawn").renderResult(
{
content: [{ type: "text", text: "failed" }],
details: { model: "m", thinking: "low", truncated: false, outcome: "error" },
},
{ expanded: false },