-
-
Notifications
You must be signed in to change notification settings - Fork 678
Expand file tree
/
Copy pathAgentSession.test.ts
More file actions
2567 lines (2349 loc) · 87.7 KB
/
Copy pathAgentSession.test.ts
File metadata and controls
2567 lines (2349 loc) · 87.7 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 { AI_SENDER, USER_SENDER } from "@/constants";
import type { TFile } from "obsidian";
import { AgentSession, buildPromptBlocks, tryReadExitPlanModeCall } from "./AgentSession";
import { AuthRequiredError, MethodUnsupportedError } from "./errors";
import type {
AgentToolCallOutput,
BackendDescriptor,
BackendProcess,
BackendState,
SessionEvent,
SessionUpdateHandler,
} from "./types";
jest.mock("@/logger", () => ({
logInfo: jest.fn(),
logWarn: jest.fn(),
logError: jest.fn(),
}));
jest.mock("@/settings/model", () => ({
getSettings: jest.fn().mockReturnValue({ agentMode: { mcpServers: [] } }),
}));
interface MockBackend {
asBackend: BackendProcess;
registerHandler: jest.Mock;
emit: (event: SessionEvent) => void;
prompt: jest.Mock;
cancel: jest.Mock;
newSession: jest.Mock;
setSessionModel: jest.Mock;
setSessionConfigOption: jest.Mock;
setSessionMode: jest.Mock;
listSessions: jest.Mock;
}
function emptyState(): BackendState {
return { model: null, mode: null };
}
function makeMockBackend(): MockBackend {
let handler: SessionUpdateHandler | null = null;
const registerHandler = jest.fn((_id: string, h: SessionUpdateHandler) => {
handler = h;
return () => {
handler = null;
};
});
const prompt = jest.fn(async () => ({ stopReason: "end_turn" as const }));
const cancel = jest.fn(async () => undefined);
const newSession = jest.fn(async () => ({ sessionId: "acp-1", state: emptyState() }));
const setSessionModel = jest.fn(async () => emptyState());
const setSessionConfigOption = jest.fn(async () => emptyState());
const setSessionMode = jest.fn(async () => emptyState());
const listSessions = jest.fn(async () => ({ sessions: [] }));
const backend: BackendProcess = {
isRunning: () => true,
onExit: () => () => {},
setPermissionPrompter: () => {},
registerSessionHandler: registerHandler,
newSession: newSession,
prompt: prompt,
cancel: cancel,
setSessionModel: setSessionModel,
isSetSessionModelSupported: () => true,
setSessionMode: setSessionMode,
isSetSessionModeSupported: () => true,
setSessionConfigOption: setSessionConfigOption,
isSetSessionConfigOptionSupported: () => true,
listSessions: listSessions,
resumeSession: () => Promise.reject(new MethodUnsupportedError("resume")),
loadSession: () => Promise.reject(new MethodUnsupportedError("load")),
supportsMcpTransport: () => false,
shutdown: async () => {},
};
return {
asBackend: backend,
registerHandler,
prompt,
cancel,
newSession,
setSessionModel,
setSessionConfigOption,
setSessionMode,
listSessions,
emit: (event) => handler?.(event),
};
}
/** Descriptor stub for a backend that summarizes its own titles (opencode). */
function summarizingDescriptor(): BackendDescriptor {
return { summarizesSessionTitle: true } as unknown as BackendDescriptor;
}
/** Descriptor stub for a backend that does NOT summarize (codex, Claude Code). */
function nonSummarizingDescriptor(): BackendDescriptor {
return { summarizesSessionTitle: false } as unknown as BackendDescriptor;
}
describe("buildPromptBlocks", () => {
// eslint-disable-next-line obsidianmd/no-tfile-tfolder-cast -- test fixture; not a real TFile
const makeFile = (path: string) => ({ path }) as unknown as TFile;
it("returns plain text when no context is attached", () => {
expect(buildPromptBlocks("hello")).toEqual([{ type: "text", text: "hello" }]);
});
it("returns plain text when context has no notes or excerpts", () => {
const blocks = buildPromptBlocks("hello", { notes: [], urls: [] });
expect(blocks).toEqual([{ type: "text", text: "hello" }]);
});
it("wraps the message with note paths when contextNotes are attached", () => {
const blocks = buildPromptBlocks("summarize them", {
notes: [makeFile("daily/2026-04-28.md"), makeFile("projects/copilot.md")],
urls: [],
});
expect(blocks).toHaveLength(1);
expect(blocks[0].type).toBe("text");
const text = (blocks[0] as { type: "text"; text: string }).text;
expect(text).toContain("<copilot-context>");
expect(text).toContain("- daily/2026-04-28.md");
expect(text).toContain("- projects/copilot.md");
expect(text).toContain("</copilot-context>");
expect(text).toContain("<user-message>\nsummarize them\n</user-message>");
});
it("inlines selected text excerpts with path and line range", () => {
const blocks = buildPromptBlocks("explain", {
notes: [],
urls: [],
selectedTextContexts: [
{
id: "s1",
sourceType: "note",
notePath: "projects/copilot.md",
noteTitle: "copilot",
startLine: 12,
endLine: 18,
content: "line one\nline two",
},
],
});
const text = (blocks[0] as { type: "text"; text: string }).text;
expect(text).toContain("Selected excerpts");
expect(text).toContain("- projects/copilot.md (lines 12-18):");
expect(text).toContain(" line one");
expect(text).toContain(" line two");
});
it("appends image content blocks after the text envelope", () => {
const blocks = buildPromptBlocks("here", undefined, [
{ type: "image", mimeType: "image/png", data: "aGVsbG8=" },
]);
expect(blocks).toEqual([
{ type: "text", text: "here" },
{ type: "image", mimeType: "image/png", data: "aGVsbG8=" },
]);
});
it("combines envelope, text, and content blocks in order", () => {
const blocks = buildPromptBlocks(
"look at this",
{
notes: [makeFile("a.md")],
urls: [],
},
[
{ type: "text", text: "<attached-pdf path='b.pdf'>parsed body</attached-pdf>" },
{ type: "image", mimeType: "image/jpeg", data: "ZmFrZQ==" },
]
);
expect(blocks).toHaveLength(3);
expect(blocks[0].type).toBe("text");
const head = (blocks[0] as { type: "text"; text: string }).text;
expect(head).toContain("<copilot-context>");
expect(head).toContain("- a.md");
expect(head).toContain("<user-message>\nlook at this\n</user-message>");
expect(blocks[1]).toEqual({
type: "text",
text: "<attached-pdf path='b.pdf'>parsed body</attached-pdf>",
});
expect(blocks[2]).toEqual({ type: "image", mimeType: "image/jpeg", data: "ZmFrZQ==" });
});
it("serializes web-source selected text excerpts as <web_selected_text>", () => {
const blocks = buildPromptBlocks("explain", {
notes: [],
urls: [],
selectedTextContexts: [
{
id: "w1",
sourceType: "web",
title: "Example",
url: "https://example.com",
content: "web snippet",
},
],
});
const text = (blocks[0] as { type: "text"; text: string }).text;
expect(text).toContain("<web_selected_text>");
expect(text).toContain("<title>Example</title>");
expect(text).toContain("<url>https://example.com</url>");
expect(text).toContain("web snippet");
expect(text).toContain("<user-message>\nexplain\n</user-message>");
});
it("weaves the web-tab block before the user message", () => {
const webTabBlock =
"<active_web_tab>\n<title>Docs</title>\n<url>https://x.dev</url>\n<content>\nhello\n</content>\n</active_web_tab>";
const blocks = buildPromptBlocks("read it", { notes: [], urls: [] }, undefined, webTabBlock);
expect(blocks).toHaveLength(1);
const text = (blocks[0] as { type: "text"; text: string }).text;
expect(text).toContain("<active_web_tab>");
expect(text).toContain("<url>https://x.dev</url>");
expect(text).toContain("<user-message>\nread it\n</user-message>");
// Context (web-tab content) precedes the user message.
expect(text.indexOf("<active_web_tab>")).toBeLessThan(text.indexOf("<user-message>"));
});
it("emits plain text when the web-tab block is empty/whitespace", () => {
const blocks = buildPromptBlocks("hi", undefined, undefined, " ");
expect(blocks).toEqual([{ type: "text", text: "hi" }]);
});
it("orders the envelope, web selections, and web-tab block before the message", () => {
const webTabBlock = "<web_tab_context>\n<url>https://x.dev</url>\n</web_tab_context>";
const blocks = buildPromptBlocks(
"look",
{
notes: [makeFile("a.md")],
urls: [],
selectedTextContexts: [
{ id: "w1", sourceType: "web", title: "W", url: "https://w.dev", content: "snip" },
],
},
undefined,
webTabBlock
);
const text = (blocks[0] as { type: "text"; text: string }).text;
const envelopePos = text.indexOf("<copilot-context>");
const selectionPos = text.indexOf("<web_selected_text>");
const webTabPos = text.indexOf("<web_tab_context>");
const messagePos = text.indexOf("<user-message>");
expect(envelopePos).toBeGreaterThanOrEqual(0);
expect(envelopePos).toBeLessThan(selectionPos);
expect(selectionPos).toBeLessThan(webTabPos);
expect(webTabPos).toBeLessThan(messagePos);
});
});
describe("AgentSession.loadDisplayMessages", () => {
it("replaces the transcript and notifies subscribers so an open view re-renders", () => {
const mock = makeMockBackend();
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
const onMessagesChanged = jest.fn();
session.subscribe({ onMessagesChanged, onStatusChanged: () => {} });
session.loadDisplayMessages([
{
id: "m0",
sender: USER_SENDER,
message: "earlier prompt",
isVisible: true,
timestamp: null,
},
{ id: "m1", sender: AI_SENDER, message: "earlier reply", isVisible: true, timestamp: null },
]);
// The missing notification here was the bug: store.loadMessages alone left
// a freshly-activated tab blank until a tab switch forced a re-read.
expect(onMessagesChanged).toHaveBeenCalledTimes(1);
expect(session.hasUserVisibleMessages()).toBe(true);
expect(session.store.getDisplayMessages().map((m) => m.message)).toEqual([
"earlier prompt",
"earlier reply",
]);
});
});
describe("AgentSession.restoreLabel", () => {
function makeResumedSession(mock: ReturnType<typeof makeMockBackend>) {
return new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
}
it("an agent-sourced restored title can still be refreshed by later agent updates", () => {
const mock = makeMockBackend();
const session = makeResumedSession(mock);
session.restoreLabel("Discovered title", "agent");
expect(session.getLabel()).toBe("Discovered title");
mock.emit({
sessionId: "acp-1",
update: { sessionUpdate: "session_info_update", title: "Newer agent title" },
});
expect(session.getLabel()).toBe("Newer agent title");
});
it("a user-sourced restored title is sticky against later agent updates", () => {
const mock = makeMockBackend();
const session = makeResumedSession(mock);
session.restoreLabel("My rename", "user");
mock.emit({
sessionId: "acp-1",
update: { sessionUpdate: "session_info_update", title: "Agent title" },
});
expect(session.getLabel()).toBe("My rename");
});
});
describe("AgentSession.sendPrompt", () => {
it("appends user + placeholder synchronously and resolves on stopReason", async () => {
const mock = makeMockBackend();
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
const { userMessageId, turn } = session.sendPrompt("Hi there");
const messages = session.store.getDisplayMessages();
expect(messages).toHaveLength(2);
expect(messages[0]).toMatchObject({
id: userMessageId,
sender: USER_SENDER,
message: "Hi there",
});
expect(messages[1]).toMatchObject({ sender: AI_SENDER, message: "" });
expect(session.getStatus()).toBe("running");
const stopReason = await turn;
expect(stopReason).toBe("end_turn");
expect(session.getStatus()).toBe("idle");
expect(mock.prompt).toHaveBeenCalledWith({
sessionId: "acp-1",
prompt: [{ type: "text", text: "Hi there" }],
});
});
it("forwards image content blocks to the backend prompt", async () => {
const mock = makeMockBackend();
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
await session.sendPrompt("describe", undefined, [
{ type: "image", mimeType: "image/png", data: "aGVsbG8=" },
]).turn;
const messages = session.store.getDisplayMessages();
expect(messages[0].message).toBe("describe");
expect(messages[0].content).toBeUndefined();
expect(mock.prompt).toHaveBeenCalledWith({
sessionId: "acp-1",
prompt: [
{ type: "text", text: "describe" },
{ type: "image", mimeType: "image/png", data: "aGVsbG8=" },
],
});
});
it("rejects if a turn is already in flight", () => {
const mock = makeMockBackend();
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
session.sendPrompt("first");
expect(() => session.sendPrompt("second")).toThrow(/in flight/);
});
it("marks an empty completed turn as a visible error message", async () => {
const mock = makeMockBackend();
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
await session.sendPrompt("hi").turn;
const placeholder = session.store.getDisplayMessages().find((m) => m.sender === AI_SENDER);
expect(placeholder?.isErrorMessage).toBe(true);
expect(placeholder?.message).toMatch(/without returning any assistant text or tool activity/);
});
it("includes nested provider errors when a prompt rejects", async () => {
const mock = makeMockBackend();
const error = new Error("stream error");
(error as { cause?: unknown }).cause = {
data: {
error: {
type: "FreeUsageLimitError",
message: "Rate limit exceeded. Please try again later.",
},
},
};
mock.prompt.mockRejectedValueOnce(error);
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
await expect(session.sendPrompt("hi").turn).rejects.toThrow("stream error");
const placeholder = session.store.getDisplayMessages().find((m) => m.sender === AI_SENDER);
expect(placeholder?.isErrorMessage).toBe(true);
expect(placeholder?.message).toContain("FreeUsageLimitError");
expect(placeholder?.message).toContain("Rate limit exceeded");
});
it("surfaces a provider error stringified inside data.message (codex-acp)", async () => {
const mock = makeMockBackend();
// codex-acp reports JSON-RPC -32603 "Internal error" with the real provider
// error nested as a JSON *string* in data.message.
const error = new Error("Internal error");
(error as { data?: unknown }).data = {
message: JSON.stringify({
type: "error",
status: 400,
error: {
type: "invalid_request_error",
message:
"The 'gpt-5.5' model requires a newer version of Codex. Please upgrade to the latest app or CLI and try again.",
},
}),
codex_error_info: "other",
};
mock.prompt.mockRejectedValueOnce(error);
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "codex",
});
await expect(session.sendPrompt("hi").turn).rejects.toThrow("Internal error");
const placeholder = session.store.getDisplayMessages().find((m) => m.sender === AI_SENDER);
expect(placeholder?.isErrorMessage).toBe(true);
expect(placeholder?.message).toContain("invalid_request_error");
expect(placeholder?.message).toContain("requires a newer version of Codex");
});
it("renders a visible error (not an empty bubble) when the backend reports auth required", async () => {
const mock = makeMockBackend();
mock.prompt.mockRejectedValueOnce(new AuthRequiredError("You're not signed in to Claude."));
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "claude",
});
await expect(session.sendPrompt("hi").turn).rejects.toBeInstanceOf(AuthRequiredError);
const placeholder = session.store.getDisplayMessages().find((m) => m.sender === AI_SENDER);
expect(placeholder?.isErrorMessage).toBe(true);
expect(placeholder?.message).toContain("not signed in to Claude");
expect(session.getStatus()).toBe("error");
});
it("agent_message_chunk is appended to placeholder displayText", async () => {
const mock = makeMockBackend();
let resolvePrompt: ((v: { stopReason: "end_turn" }) => void) | null = null;
mock.prompt.mockImplementation(
() => new Promise((resolve) => (resolvePrompt = resolve as typeof resolvePrompt))
);
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
const { turn } = session.sendPrompt("hi");
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Hello" },
},
});
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: ", world." },
},
});
const placeholder = session.store.getDisplayMessages().find((m) => m.sender === AI_SENDER);
expect(placeholder?.message).toBe("Hello, world.");
resolvePrompt!({ stopReason: "end_turn" });
await turn;
});
it("appends a content chunk that trails past the prompt result (messageId race)", async () => {
const mock = makeMockBackend();
let resolvePrompt: ((v: { stopReason: "end_turn" }) => void) | null = null;
mock.prompt.mockImplementation(
() => new Promise((resolve) => (resolvePrompt = resolve as typeof resolvePrompt))
);
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
const { turn } = session.sendPrompt("hi");
// Chunk delivered before the result.
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "agent_message_chunk",
messageId: "msg-1",
content: { type: "text", text: "Hello" },
},
});
// The backend flushes the result while the last chunk is still in flight.
resolvePrompt!({ stopReason: "end_turn" });
await turn;
// Trailing chunk for the same message arrives after the turn settled.
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "agent_message_chunk",
messageId: "msg-1",
content: { type: "text", text: ", world." },
},
});
const placeholder = session.store.getDisplayMessages().find((m) => m.sender === AI_SENDER);
expect(placeholder?.message).toBe("Hello, world.");
});
it("routes a trailing chunk to its own message, not a newer turn", async () => {
const mock = makeMockBackend();
let resolvePrompt: ((v: { stopReason: "end_turn" }) => void) | null = null;
mock.prompt.mockImplementation(
() => new Promise((resolve) => (resolvePrompt = resolve as typeof resolvePrompt))
);
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
// Turn A streams under messageId msg-a, then the result is flushed early.
const { turn: turnA } = session.sendPrompt("first");
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "agent_message_chunk",
messageId: "msg-a",
content: { type: "text", text: "A-before" },
},
});
resolvePrompt!({ stopReason: "end_turn" });
await turnA;
// Turn B begins before A's trailing chunk lands.
const { turn: turnB } = session.sendPrompt("second");
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "agent_message_chunk",
messageId: "msg-b",
content: { type: "text", text: "B-text" },
},
});
// A's late chunk must follow msg-a to A's message, not append to B.
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "agent_message_chunk",
messageId: "msg-a",
content: { type: "text", text: "A-after" },
},
});
const ai = session.store.getDisplayMessages().filter((m) => m.sender === AI_SENDER);
expect(ai[0]?.message).toBe("A-beforeA-after");
expect(ai[1]?.message).toBe("B-text");
resolvePrompt!({ stopReason: "end_turn" });
await turnB;
});
it("tool_call followed by tool_call_update merges into a single part", async () => {
const mock = makeMockBackend();
let resolvePrompt: ((v: { stopReason: "end_turn" }) => void) | null = null;
mock.prompt.mockImplementation(
() => new Promise((resolve) => (resolvePrompt = resolve as typeof resolvePrompt))
);
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
const { turn } = session.sendPrompt("hi");
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "tc1",
title: "Read README",
kind: "read",
status: "pending",
rawInput: { path: "README.md" },
},
});
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tc1",
status: "completed",
content: [{ type: "content", content: { type: "text", text: "file contents" } }],
},
});
const placeholder = session.store.getDisplayMessages().find((m) => m.sender === AI_SENDER);
expect(placeholder?.parts).toHaveLength(1);
expect(placeholder?.parts?.[0]).toMatchObject({
kind: "tool_call",
id: "tc1",
title: "Read README",
status: "completed",
output: [{ type: "text", text: "file contents" }],
});
resolvePrompt!({ stopReason: "end_turn" });
await turn;
});
// Emit one completed tool call with `text` output and return the stored output.
const storedToolOutput = async (text: string): Promise<AgentToolCallOutput | undefined> => {
const mock = makeMockBackend();
let resolvePrompt: ((v: { stopReason: "end_turn" }) => void) | null = null;
mock.prompt.mockImplementation(
() => new Promise((resolve) => (resolvePrompt = resolve as typeof resolvePrompt))
);
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "codex",
});
const { turn } = session.sendPrompt("hi");
mock.emit({
sessionId: "acp-1",
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tc1",
status: "completed",
content: [{ type: "content", content: { type: "text", text } }],
},
});
const part = session.store.getDisplayMessages().find((m) => m.sender === AI_SENDER)?.parts?.[0];
resolvePrompt!({ stopReason: "end_turn" });
await turn;
if (part?.kind !== "tool_call") throw new Error("expected tool_call part");
return part.output?.[0];
};
it("stores a large (but under-cap) text tool output in full", async () => {
const text = "x".repeat(100_000);
// 100k is far below the 256k runaway backstop, so it's preserved verbatim.
expect(await storedToolOutput(text)).toEqual({ type: "text", text });
});
it("trims a runaway tool output above the backstop, noting the agent got it all", async () => {
const output = await storedToolOutput("y".repeat(300_000));
if (output?.type !== "text") throw new Error("expected text output");
expect(output.text.length).toBeLessThan(300_000);
expect(output.text).toContain("Display trimmed");
expect(output.text).toContain("The agent received the full output");
});
it("cancel() sends cancel and aborts local controller", async () => {
const mock = makeMockBackend();
let resolvePrompt: ((v: { stopReason: "cancelled" }) => void) | null = null;
mock.prompt.mockImplementation(
() => new Promise((resolve) => (resolvePrompt = resolve as typeof resolvePrompt))
);
const session = new AgentSession({
backend: mock.asBackend,
backendSessionId: "acp-1",
internalId: "internal-1",
backendId: "opencode",
});
const { turn } = session.sendPrompt("hi");
await session.cancel();
expect(mock.cancel).toHaveBeenCalledWith({ sessionId: "acp-1" });
resolvePrompt!({ stopReason: "cancelled" });
expect(await turn).toBe("cancelled");
});
});
describe("AgentSession.create (via start)", () => {
it("captures `state.model` from newSession and exposes via getState", async () => {
const mock = makeMockBackend();
const stateWithModel: BackendState = {
model: {
current: { baseModelId: "anthropic/sonnet", effort: null },
apply: { kind: "setModel" },
availableModels: [
{
baseModelId: "anthropic/sonnet",
name: "Claude Sonnet",
provider: "anthropic",
effortOptions: [],
},
{ baseModelId: "openai/gpt-5", name: "GPT-5", provider: "openai", effortOptions: [] },
],
},
mode: null,
};
mock.newSession.mockResolvedValueOnce({ sessionId: "acp-1", state: stateWithModel });
const session = AgentSession.start({
backend: mock.asBackend,
cwd: "/vault",
internalId: "internal-1",
backendId: "opencode",
});
await session.ready;
expect(session.getState()?.model?.current.baseModelId).toBe("anthropic/sonnet");
expect(session.getState()?.model?.availableModels).toHaveLength(2);
});
it("getState returns null-model when the agent doesn't report models", async () => {
const mock = makeMockBackend();
mock.newSession.mockResolvedValueOnce({ sessionId: "acp-1", state: emptyState() });
const session = AgentSession.start({
backend: mock.asBackend,
cwd: "/vault",
internalId: "internal-1",
backendId: "opencode",
});
await session.ready;
expect(session.getState()?.model).toBeNull();
});
it("attempts setModel when defaultModelSelection is set", async () => {
const mock = makeMockBackend();
const stateWithSonnet: BackendState = {
model: {
current: { baseModelId: "anthropic/sonnet", effort: null },
apply: { kind: "setModel" },
availableModels: [
{
baseModelId: "anthropic/sonnet",
name: "Claude Sonnet",
provider: "anthropic",
effortOptions: [],
},
{ baseModelId: "openai/gpt-5", name: "GPT-5", provider: "openai", effortOptions: [] },
],
},
mode: null,
};
mock.newSession.mockResolvedValueOnce({ sessionId: "acp-1", state: stateWithSonnet });
const session = AgentSession.start({
backend: mock.asBackend,
cwd: "/vault",
internalId: "internal-1",
backendId: "opencode",
defaultModelSelection: { baseModelId: "openai/gpt-5", effort: null },
getDescriptor: () => makeWireOnlyDescriptor(),
});
await session.ready;
expect(mock.setSessionModel).toHaveBeenCalledWith({
sessionId: "acp-1",
modelId: "openai/gpt-5",
});
});
it("applyModelWireId routes through set_config_option when the catalog is config-option-backed", async () => {
const mock = makeMockBackend();
const configBackedState: BackendState = {
model: {
current: { baseModelId: "omlx/a", effort: null },
apply: { kind: "setConfigOption", configId: "model" },
availableModels: [{ baseModelId: "omlx/a", name: "A", provider: null, effortOptions: [] }],
},
mode: null,
};
mock.newSession.mockResolvedValueOnce({ sessionId: "acp-1", state: configBackedState });
const session = AgentSession.start({
backend: mock.asBackend,
cwd: "/vault",
internalId: "internal-1",
backendId: "opencode",
});
await session.ready;
await session.applyModelWireId("omlx/b");
expect(mock.setSessionConfigOption).toHaveBeenCalledWith({
sessionId: "acp-1",
configId: "model",
value: "omlx/b",
});
expect(mock.setSessionModel).not.toHaveBeenCalled();
});
it("applyModelWireId routes through set_model when the catalog is models-backed", async () => {
const mock = makeMockBackend();
const modelsBackedState: BackendState = {
model: {
current: { baseModelId: "gpt-5", effort: null },
apply: { kind: "setModel" },
availableModels: [
{ baseModelId: "gpt-5", name: "GPT-5", provider: null, effortOptions: [] },
],
},
mode: null,
};
mock.newSession.mockResolvedValueOnce({ sessionId: "acp-1", state: modelsBackedState });
const session = AgentSession.start({
backend: mock.asBackend,
cwd: "/vault",
internalId: "internal-1",
backendId: "codex",
});
await session.ready;
await session.applyModelWireId("o3");
expect(mock.setSessionModel).toHaveBeenCalledWith({ sessionId: "acp-1", modelId: "o3" });
expect(mock.setSessionConfigOption).not.toHaveBeenCalled();
});
it("seeds currentState with the persisted selection before notifying listeners", async () => {
const mock = makeMockBackend();
const stateWithSonnet: BackendState = {
model: {
current: { baseModelId: "anthropic/sonnet", effort: null },
apply: { kind: "setModel" },
availableModels: [
{
baseModelId: "anthropic/sonnet",
name: "Claude Sonnet",
provider: "anthropic",
effortOptions: [],
},
{ baseModelId: "openai/gpt-5", name: "GPT-5", provider: "openai", effortOptions: [] },
],
},
mode: null,
};
mock.newSession.mockResolvedValueOnce({ sessionId: "acp-1", state: stateWithSonnet });
// Block setSessionModel so the seed must survive on its own — without
// the optimistic seed the picker would see "anthropic/sonnet" first.
let resolveSetModel: ((s: BackendState) => void) | null = null;
mock.setSessionModel.mockImplementationOnce(
() => new Promise<BackendState>((resolve) => (resolveSetModel = resolve))
);
const session = AgentSession.start({
backend: mock.asBackend,
cwd: "/vault",
internalId: "internal-1",
backendId: "opencode",
defaultModelSelection: { baseModelId: "openai/gpt-5", effort: null },
getDescriptor: () => makeWireOnlyDescriptor(),
});
const observed: Array<string | undefined> = [];
session.subscribe({
onMessagesChanged: jest.fn(),
onStatusChanged: jest.fn(),
onModelChanged: () => observed.push(session.getState()?.model?.current.baseModelId),
});
// Wait for the first notifyModelChanged inside initialize.
await Promise.resolve();
await Promise.resolve();
expect(observed[0]).toBe("openai/gpt-5");
resolveSetModel!(stateWithSonnet);
await session.ready;
});
it("eagerly seeds currentState from initialCachedState before newSession resolves", async () => {
const mock = makeMockBackend();
const cachedState: BackendState = {
model: {
current: { baseModelId: "kimi-2.6", effort: null },
apply: { kind: "setModel" },
availableModels: [
{ baseModelId: "kimi-2.6", name: "Kimi 2.6", provider: "moon", effortOptions: [] },
{
baseModelId: "big-pickle",
name: "Big Pickle",
provider: "moon",
effortOptions: [],
},
],
},
mode: null,
};
// Block newSession so we can observe the pre-initialize state.
let resolveNewSession: ((r: { sessionId: string; state: BackendState }) => void) | null = null;
mock.newSession.mockImplementationOnce(
() =>
new Promise<{ sessionId: string; state: BackendState }>(
(resolve) => (resolveNewSession = resolve)
)
);
const session = AgentSession.start({
backend: mock.asBackend,
cwd: "/vault",
internalId: "internal-1",
backendId: "opencode",
defaultModelSelection: { baseModelId: "big-pickle", effort: null },
initialCachedState: cachedState,
getDescriptor: () => makeWireOnlyDescriptor(),
});
// Before newSession resolves, getState reflects the eager seed
// (current = big-pickle) rather than the cached current (kimi-2.6).
expect(session.getState()?.model?.current.baseModelId).toBe("big-pickle");
resolveNewSession!({ sessionId: "acp-1", state: cachedState });
await session.ready;
});
it("does not seed effort into currentState (effort stays as backend reported)", async () => {
// Regression: previously, the optimistic seed wrote both `baseModelId`
// and `effort` into currentState. For descriptor-style backends where
// effort lives outside the wire id, `applyInitialSessionConfig` would
// see the seeded effort match the persisted effort and skip the real
// `setConfigOption`, silently dropping the user's persisted effort.
const mock = makeMockBackend();
const backendState: BackendState = {
model: {
current: { baseModelId: "anthropic/sonnet", effort: "low" },
apply: { kind: "setModel" },
availableModels: [
{
baseModelId: "anthropic/sonnet",
name: "Claude Sonnet",
provider: "anthropic",
effortOptions: [
{ value: "low", label: "Low" },
{ value: "high", label: "High" },
],
},
],
},
mode: null,
};
mock.newSession.mockResolvedValueOnce({ sessionId: "acp-1", state: backendState });
const session = AgentSession.start({
backend: mock.asBackend,
cwd: "/vault",
internalId: "internal-1",
backendId: "claude",
defaultModelSelection: { baseModelId: "anthropic/sonnet", effort: "high" },
// Descriptor whose wire encoding ignores effort (Claude-style).
getDescriptor: () => makeDescriptorWireWithoutEffort(),
});
await session.ready;
// baseModelId matches → no setModel call needed.
expect(mock.setSessionModel).not.toHaveBeenCalled();
// Effort is what the backend reported, NOT the persisted "high" — so
// `applyInitialSessionConfig` will see a mismatch and call setConfigOption.
expect(session.getState()?.model?.current.effort).toBe("low");
});
it("reverts the seeded selection when setModel fails", async () => {
const mock = makeMockBackend();
const stateWithSonnet: BackendState = {
model: {
current: { baseModelId: "anthropic/sonnet", effort: null },
apply: { kind: "setModel" },
availableModels: [
{
baseModelId: "anthropic/sonnet",
name: "Claude Sonnet",
provider: "anthropic",