Repository navigation
Expand file tree
/
Copy pathchannel.test.ts
More file actions
1865 lines (1712 loc) · 60.9 KB
/
Copy pathchannel.test.ts
File metadata and controls
1865 lines (1712 loc) · 60.9 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 type {
AgentSubscriber,
RunAgentParameters,
RunAgentResult,
} from "@ag-ui/client";
import { EventType } from "@ag-ui/client";
import { afterEach, describe, expect, it, vi } from "vitest";
// The button asks the agent which provider it runs. A unit test has no agent,
// so the answer is stubbed; each test that cares sets `provider.current`.
const provider = vi.hoisted(() => ({
current: "composio" as "composio" | "arcade" | null | undefined,
}));
vi.mock("./tools/arcade-connect.js", async (original) => ({
...(await original<typeof import("./tools/arcade-connect.js")>()),
lookupConnectedAppProvider: vi.fn(async () => provider.current),
}));
import {
FakeAdapter,
FakeAgent,
MemoryStore,
type Channel,
type ChannelNode,
} from "@copilotkit/channels";
import {
defaultSlackContext,
defaultSlackTools,
renderSlackMessage,
} from "@copilotkit/channels/slack";
import { appContext } from "./context/app-context.js";
import { appTools } from "./tools/index.js";
import { RenderChart } from "./tools/render-chart.js";
import { createOpenTagChannel } from "./channel.js";
import {
subscribeThreadTool,
unsubscribeThreadTool,
} from "./tools/thread-subscription.js";
class CapturingAgent extends FakeAgent {
readonly calls: Array<RunAgentParameters | undefined>;
readonly messageSnapshots: unknown[][];
constructor(
calls: Array<RunAgentParameters | undefined> = [],
messageSnapshots: unknown[][] = [],
) {
super();
this.calls = calls;
this.messageSnapshots = messageSnapshots;
}
override clone(): CapturingAgent {
const cloned = new CapturingAgent(this.calls, this.messageSnapshots);
cloned.threadId = this.threadId;
cloned.agentId = this.agentId;
cloned.messages = structuredClone(this.messages);
cloned.state = structuredClone(this.state);
return cloned;
}
override async runAgent(
parameters?: RunAgentParameters,
subscriber?: AgentSubscriber,
): Promise<RunAgentResult> {
this.calls.push(parameters);
this.messageSnapshots.push(structuredClone(this.messages));
return super.runAgent(parameters, subscriber);
}
}
type AgentStep = (subscriber: AgentSubscriber) => void | Promise<void>;
class SharedScriptAgent extends FakeAgent {
constructor(
private readonly steps: AgentStep[],
readonly calls: Array<RunAgentParameters | undefined> = [],
) {
super();
}
override clone(): SharedScriptAgent {
const cloned = new SharedScriptAgent(this.steps, this.calls);
cloned.threadId = this.threadId;
cloned.agentId = this.agentId;
cloned.messages = structuredClone(this.messages);
cloned.state = structuredClone(this.state);
return cloned;
}
override async runAgent(
parameters?: RunAgentParameters,
subscriber?: AgentSubscriber,
): Promise<RunAgentResult> {
this.calls.push(parameters);
const step = this.steps.shift();
if (step && subscriber) await step(subscriber);
return { result: undefined, newMessages: [] };
}
}
function callTool(name: string, id: string): AgentStep {
return (subscriber) => {
subscriber.onToolCallEndEvent?.({
event: { toolCallId: id },
toolCallName: name,
toolCallArgs: {},
} as never);
};
}
function toolNames(call: RunAgentParameters | undefined): string[] {
return call?.tools?.map(({ name }) => name) ?? [];
}
const channels: Channel[] = [];
function confirmWriteEnvelope(
action = "Create Linear issue",
detail: string | null = "CPK-9: Checkout 500s",
extraArgs: Record<string, unknown> = {},
) {
return {
__opentag_interrupt_id__: crypto.randomUUID().replaceAll("-", ""),
__copilotkit_interrupt_value__: {
action: "confirm_write",
args: { action, detail, ...extraArgs },
},
__copilotkit_messages__: [
{
content: "",
type: "ai",
tool_calls: [
{
id: "tool-confirm-write",
name: "confirm_write",
args: { action, detail },
type: "tool_call",
},
],
},
],
};
}
function findButton(
nodes: ChannelNode[],
confirmed: boolean,
): ChannelNode | undefined {
for (const node of nodes) {
if (
node.type === "button" &&
(node.props.value as { confirmed?: boolean } | undefined)?.confirmed ===
confirmed
) {
return node;
}
const children = node.props.children;
if (Array.isArray(children)) {
const found = findButton(children as ChannelNode[], confirmed);
if (found) return found;
}
}
return undefined;
}
/** The Connect button carrying one toolkit, anywhere in a posted card. */
function findButtonByToolkit(
nodes: ChannelNode[],
toolkit: string,
): ChannelNode | undefined {
for (const node of nodes) {
if (
node.type === "button" &&
(node.props.value as { toolkit?: string } | undefined)?.toolkit === toolkit
) {
return node;
}
const children = node.props.children;
if (Array.isArray(children)) {
const found = findButtonByToolkit(children as ChannelNode[], toolkit);
if (found) return found;
}
}
return undefined;
}
function findIncidentButton(
nodes: ChannelNode[],
action: "ack" | "escalate",
): ChannelNode | undefined {
for (const node of nodes) {
if (
node.type === "button" &&
(node.props.value as { action?: string } | undefined)?.action === action
) {
return node;
}
const children = node.props.children;
if (Array.isArray(children)) {
const found = findIncidentButton(children as ChannelNode[], action);
if (found) return found;
}
}
return undefined;
}
afterEach(async () => {
await Promise.all(
channels.splice(0).map((channel) => channel.ɵruntime.stop()),
);
vi.restoreAllMocks();
// Here rather than at the end of the one test that stubs, because the end of
// a test is exactly where a failing test does not reach: a stubbed
// `AGENT_URL` would then leak into every test after it, and the suite would
// report the leak as a second failure somewhere unrelated.
vi.unstubAllEnvs();
});
function makeChannel(
options: { agent?: FakeAgent; agentDisplayName?: string } = {},
) {
const adapter = new FakeAdapter({ platform: "intelligence" });
const stateStore = new MemoryStore();
adapter.stateStore = stateStore;
const agent = options.agent ?? new CapturingAgent();
const channel = createOpenTagChannel(
"opentag",
agent,
options.agentDisplayName,
);
channel.ɵruntime.addAdapter(adapter);
channels.push(channel);
return { adapter, agent, channel, stateStore };
}
describe("createOpenTagChannel", () => {
it("uses the configured identity in agent context and capability tooling", async () => {
const { adapter, agent, channel } = makeChannel({
agentDisplayName: "Kite",
});
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "identity-thread",
replyTarget: {},
userText: "@Kite who are you?",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m1",
revisionId: "m1",
mentioned: true,
},
});
const call = (agent as CapturingAgent).calls[0];
expect(call?.context).toEqual(
expect.arrayContaining([
expect.objectContaining({
description: "Bot identity & tone",
value: expect.stringContaining(
"CRITICAL: Your user-facing name is Kite",
),
}),
]),
);
expect(
call?.tools?.find(({ name }) => name === "show_capabilities")
?.description,
).toContain("Show Kite's interactive identity");
});
it("does not answer a revision of a message it already answered", async () => {
// The reply loop. Posting an answer counts as a change to the message that
// asked, so Slack re-announces that message with a fresh revision id and
// the ORIGINAL author still on it — indistinguishable from the person
// asking again, unless the revision itself is read. One mention here
// produced about fifty answers in a live workspace.
const { adapter, agent, channel } = makeChannel();
await channel.ɵruntime.start();
const ask = {
conversationKey: "loop-thread",
replyTarget: {},
userText: "@OpenTag say hi",
platform: "slack" as const,
actor: { id: "U1", kind: "human" as const },
};
await adapter.getSink().onTurn({
...ask,
operation: {
kind: "created" as const,
logicalMessageId: "m1",
revisionId: "m1",
mentioned: true,
},
});
const afterFirstAnswer = (agent as CapturingAgent).calls.length;
expect(afterFirstAnswer).toBe(1);
// Same message, new revision, because the answer landed in its thread.
await adapter.getSink().onTurn({
...ask,
operation: {
kind: "updated" as const,
logicalMessageId: "m1",
revisionId: "m1-r2",
mentioned: true,
},
});
expect((agent as CapturingAgent).calls.length).toBe(afterFirstAnswer);
});
it("subscribes a new mentioned conversation and handles a later managed delivery", async () => {
const { adapter, agent, channel, stateStore } = makeChannel();
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "mentioned-thread",
replyTarget: {},
userText: "@Kite help me triage this",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m1",
revisionId: "m1",
mentioned: true,
},
});
expect(await stateStore.kv.get<boolean>("sub:mentioned-thread")).toBe(true);
expect(toolNames((agent as CapturingAgent).calls[0])).toContain(
unsubscribeThreadTool.name,
);
expect(toolNames((agent as CapturingAgent).calls[0])).not.toContain(
subscribeThreadTool.name,
);
await adapter.getSink().onTurn({
conversationKey: "mentioned-thread",
replyTarget: {},
userText: "What should I do first?",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m2",
revisionId: "m2",
mentioned: false,
},
});
expect((agent as CapturingAgent).calls).toHaveLength(2);
expect(toolNames((agent as CapturingAgent).calls[1])).toContain(
unsubscribeThreadTool.name,
);
});
it("keeps an existing unsubscribed conversation mention-only and offers subscribe", async () => {
const { adapter, agent, channel, stateStore } = makeChannel();
adapter.messages = [
{ text: "existing root", ts: "1" },
{ text: "@Kite answer this", ts: "2" },
];
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "existing-thread",
replyTarget: {},
userText: "@Kite answer this",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m2",
revisionId: "m2",
mentioned: true,
},
});
expect(await stateStore.kv.get<boolean>("sub:existing-thread")).toBeUndefined();
expect(toolNames((agent as CapturingAgent).calls[0])).toContain(
subscribeThreadTool.name,
);
expect(toolNames((agent as CapturingAgent).calls[0])).not.toContain(
unsubscribeThreadTool.name,
);
});
it("offers unsubscribe on a mention in an already subscribed conversation", async () => {
const { adapter, agent, channel, stateStore } = makeChannel();
await stateStore.kv.set("sub:subscribed-thread", true);
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "subscribed-thread",
replyTarget: {},
userText: "@Kite status?",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m2",
revisionId: "m2",
mentioned: true,
},
});
expect(toolNames((agent as CapturingAgent).calls[0])).toContain(
unsubscribeThreadTool.name,
);
expect(toolNames((agent as CapturingAgent).calls[0])).not.toContain(
subscribeThreadTool.name,
);
});
it("answers a mention without following the thread when the history is unreadable", async () => {
// Following a thread is a standing commitment to answer everything said in
// it from here on. Taking it because a history read failed is deciding on
// evidence nobody has — and it is not the cheap direction: not following
// costs the user one sentence, and the run is still offered the tool to
// act on it.
const consoleError = vi
.spyOn(console, "error")
.mockImplementation(() => undefined);
const { adapter, agent, channel, stateStore } = makeChannel();
adapter.getMessages = vi.fn(async () => {
throw new Error("history unavailable");
});
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "history-failure",
replyTarget: {},
userText: "@Kite help",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m1",
revisionId: "m1",
mentioned: true,
},
});
// The mention is answered either way. That is the part that must not
// depend on a history read.
expect((agent as CapturingAgent).calls).toHaveLength(1);
expect(
await stateStore.kv.get<boolean>("sub:history-failure"),
).toBeUndefined();
expect(toolNames((agent as CapturingAgent).calls[0])).toContain(
subscribeThreadTool.name,
);
expect(consoleError).toHaveBeenCalledWith(
"[channel] recoverable error",
expect.objectContaining({
context: {
operation: "get_thread_history",
recovery: "answered_without_following",
},
}),
);
});
it("ignores unmentioned turns after unsubscribe and resumes them after subscribe", async () => {
const agent = new SharedScriptAgent([
callTool(unsubscribeThreadTool.name, "unsubscribe-1"),
() => undefined,
callTool(subscribeThreadTool.name, "subscribe-1"),
() => undefined,
() => undefined,
]);
const { adapter, channel, stateStore } = makeChannel({ agent });
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "toggle-thread",
replyTarget: {},
userText: "@Kite only answer mentions from now on",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m1",
revisionId: "m1",
mentioned: true,
},
});
expect(await stateStore.kv.get<boolean>("sub:toggle-thread")).toBeUndefined();
expect(toolNames(agent.calls[0])).toContain(unsubscribeThreadTool.name);
await adapter.getSink().onTurn({
conversationKey: "toggle-thread",
replyTarget: {},
userText: "this should be ignored",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m2",
revisionId: "m2",
mentioned: false,
},
});
expect(agent.calls).toHaveLength(2);
adapter.messages = [
{ text: "existing root", ts: "1" },
{ text: "@Kite start following again", ts: "3" },
];
await adapter.getSink().onTurn({
conversationKey: "toggle-thread",
replyTarget: {},
userText: "@Kite start following again",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m3",
revisionId: "m3",
mentioned: true,
},
});
expect(await stateStore.kv.get<boolean>("sub:toggle-thread")).toBe(true);
expect(toolNames(agent.calls[2])).toContain(subscribeThreadTool.name);
await adapter.getSink().onTurn({
conversationKey: "toggle-thread",
replyTarget: {},
userText: "this should run",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m4",
revisionId: "m4",
mentioned: false,
},
});
expect(agent.calls).toHaveLength(5);
expect(toolNames(agent.calls[4])).toContain(unsubscribeThreadTool.name);
});
// `composio_tools.state.PERSONAL_KINDS` admits `human` and nothing else, on
// the grounds that `ProviderActor.kind` is the provider's own untrusted word
// for what sent a message. A surface-side filter that stops at `bot`/`app`
// hands the other two a turn the agent would never have granted an identity.
it.each(["bot", "app", "system", "unknown"] as const)(
"ignores %s-authored messages in a subscribed thread",
async (actorKind) => {
const { adapter, agent, channel } = makeChannel();
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "bot-loop-thread",
replyTarget: {},
userText: "@Kite join us",
platform: "slack",
actor: { id: "U1", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m1",
revisionId: "m1",
mentioned: true,
},
});
await adapter.getSink().onTurn({
conversationKey: "bot-loop-thread",
replyTarget: {},
userText: "Canonical status confirmed: vibing cat it is.",
platform: "slack",
actor: { id: "B1", kind: actorKind },
operation: {
kind: "created",
logicalMessageId: "m2",
revisionId: "m2",
mentioned: false,
},
});
await adapter.getSink().onTurn({
conversationKey: "bot-loop-thread",
replyTarget: {},
userText: "@Kite automated follow-up",
platform: "slack",
actor: { id: "B1", kind: actorKind },
operation: {
kind: "created",
logicalMessageId: "m3",
revisionId: "m3",
mentioned: true,
},
});
expect((agent as CapturingAgent).calls).toHaveLength(1);
},
);
it("ignores an unmentioned turn in an unsubscribed thread", async () => {
const { adapter, agent, channel } = makeChannel();
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "managed-thread",
replyTarget: {},
userText: "This thread is not subscribed",
platform: "slack",
actor: { id: "U2", kind: "human" },
operation: {
kind: "created",
logicalMessageId: "m1",
revisionId: "m1",
mentioned: false,
},
});
expect((agent as CapturingAgent).calls).toHaveLength(0);
});
it("declares one managed Channel and retains app commands", () => {
const channel = createOpenTagChannel("custom-channel", new FakeAgent());
channels.push(channel);
expect(channel.name).toBe("custom-channel");
expect(channel.adapters).toEqual([]);
expect(channel.commandNames.sort()).toEqual([
"agent",
"file_issue",
"preview",
"triage",
]);
expect(appTools.map(({ name }) => name).sort()).toEqual([
"connect_app",
"issue_card",
"issue_list",
"page_list",
"read_thread",
"render_diagram",
"render_table",
"show_capabilities",
"show_decision_brief",
"show_incident",
"show_knowledge_summary",
"show_links",
"show_status",
"show_work_plan",
]);
expect(RenderChart.name).toBe("render_chart");
expect(appTools.map(({ name }) => name)).not.toContain("confirm_write");
});
it("renders render_chart through the registered Channel component", async () => {
const agent = new FakeAgent([
(subscriber) => {
subscriber.onToolCallEndEvent?.({
event: { toolCallId: "chart-1" },
toolCallName: RenderChart.name,
toolCallArgs: {
title: "Incidents",
chart: {
type: "pie",
segments: [
{ label: "SEV1", value: 2 },
{ label: "SEV2", value: 5 },
],
},
},
} as never);
},
() => undefined,
]);
const { adapter, channel } = makeChannel({ agent });
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "chart-thread",
replyTarget: {},
userText: "chart incidents by severity",
platform: "slack",
actor: { id: "U1", kind: "human" },
});
expect(adapter.posted).toHaveLength(1);
const { blocks } = renderSlackMessage(adapter.posted[0]!);
expect(blocks[0]).toMatchObject({
type: "data_visualization",
title: "Incidents",
chart: {
type: "pie",
segments: [
{ label: "SEV1", value: 2 },
{ label: "SEV2", value: 5 },
],
},
});
});
it("injects Slack defaults per managed Slack run", async () => {
const { adapter, agent, channel } = makeChannel();
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "c1",
replyTarget: {},
userText: "hello",
platform: "slack",
actor: { id: "U1", kind: "human", name: "Ada" },
});
const call = (agent as CapturingAgent).calls[0];
expect(call?.tools?.map(({ name }) => name).sort()).toEqual(
[
...appTools.map(({ name }) => name),
RenderChart.name,
...defaultSlackTools.map(({ name }) => name),
unsubscribeThreadTool.name,
].sort(),
);
expect(call?.context).toEqual([
...appContext,
...defaultSlackContext,
{
description: "Requesting slack user",
value: "Ada (slack id U1)",
},
]);
});
it("does not inject Slack defaults into managed Teams", async () => {
const { adapter, agent, channel } = makeChannel();
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "c1",
replyTarget: {},
userText: "hello",
platform: "teams",
actor: { id: "T1", kind: "human", name: "Ada" },
});
const call = (agent as CapturingAgent).calls[0];
expect(call?.tools?.map(({ name }) => name).sort()).toEqual(
[
...appTools.map(({ name }) => name),
RenderChart.name,
unsubscribeThreadTool.name,
].sort(),
);
expect(call?.context).toEqual([
...appContext,
{
description: "Requesting teams user",
value: "Ada (teams id T1)",
},
]);
});
it("injects managed content parts as the current agent prompt", async () => {
const { adapter, agent, channel } = makeChannel();
const parts = [{ type: "text" as const, text: "from content parts" }];
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "c1",
replyTarget: {},
userText: "fallback text",
contentParts: parts,
platform: "slack",
actor: { id: "U1", kind: "human" },
});
expect((agent as CapturingAgent).messageSnapshots.flat()).toContainEqual(
expect.objectContaining({ role: "user", content: parts }),
);
});
it("suggests knowledge-work prompts when a thread starts", async () => {
const { adapter, channel } = makeChannel();
await channel.ɵruntime.start();
await adapter.emitThreadStarted({
conversationKey: "c1",
replyTarget: {},
actor: { id: "U1", kind: "human", name: "Ada" },
});
expect(adapter.suggestedPromptsCalls[0]?.prompts).toEqual([
{
title: "Synthesize this discussion",
message:
"Summarize this thread into key findings, decisions, open questions, and next steps",
},
{
title: "Help me make a decision",
message:
"Compare the options in this thread and recommend a path forward",
},
]);
});
it("surfaces a structured recoverable error when suggested prompts fail", async () => {
const consoleError = vi
.spyOn(console, "error")
.mockImplementation(() => undefined);
const { adapter, channel } = makeChannel();
adapter.setSuggestedPrompts = vi.fn(async () => {
throw new Error("suggested prompts unavailable");
});
await channel.ɵruntime.start();
await adapter.emitThreadStarted({
conversationKey: "c1",
replyTarget: {},
actor: { id: "U1", kind: "human", name: "Ada" },
});
expect(consoleError).toHaveBeenCalledWith(
"[channel] recoverable error",
expect.objectContaining({
error: expect.any(Error),
context: {
operation: "set_suggested_prompts",
recovery: "continue_without_suggested_prompts",
},
timestamp: expect.any(String),
}),
);
});
it("says so when the surface cannot take suggested prompts at all", async () => {
// `Thread.setSuggestedPrompts` answers `{ ok: false }` on a surface with no
// such pane — it does not throw. A `try`/`catch` around it is watching the
// one door this failure never comes through, and the prompts are simply
// missing with nothing anywhere saying why.
const consoleError = vi
.spyOn(console, "error")
.mockImplementation(() => undefined);
const adapter = new FakeAdapter({
platform: "intelligence",
paneMethods: false,
});
adapter.stateStore = new MemoryStore();
const channel = createOpenTagChannel("opentag", new FakeAgent());
channel.ɵruntime.addAdapter(adapter);
channels.push(channel);
await channel.ɵruntime.start();
await adapter.emitThreadStarted({
conversationKey: "c1",
replyTarget: {},
actor: { id: "U1", kind: "human", name: "Ada" },
});
expect(adapter.suggestedPromptsCalls).toHaveLength(0);
expect(JSON.stringify(consoleError.mock.calls)).toContain(
"set_suggested_prompts",
);
consoleError.mockRestore();
});
it("logs the pair when the agent run and its error reply both fail", async () => {
// Thrown out of an unguarded handler, this is the one failure in the file
// that leaves no trace of its own: the Channel takes the throw, and the two
// errors inside it — why the run failed, and why the user was never told —
// go with it.
const consoleError = vi
.spyOn(console, "error")
.mockImplementation(() => undefined);
const { adapter, channel } = makeChannel({
agent: new FakeAgent([
() => {
throw new Error("agent unavailable");
},
]),
});
adapter.post = vi.fn(async () => {
throw new Error("thread is archived");
});
await channel.ɵruntime.start();
// The pair is re-raised as well as logged, and this ingress reports it
// however the runtime chooses to; the assertion below is about the log.
await Promise.resolve(
adapter.getSink().onTurn({
conversationKey: "c1",
replyTarget: {},
userText: "hello",
platform: "slack",
actor: { id: "U1", kind: "human" },
}),
).catch(() => undefined);
// Read off the logged object rather than its JSON: an Error stringifies to
// `{}`, so a JSON assertion here would pass on a log carrying no reason at
// all.
const entry = consoleError.mock.calls.find(
([, payload]) =>
(payload as { context?: { operation?: string } } | undefined)?.context
?.operation === "run_agent_error_reply",
);
expect(entry).toBeDefined();
const logged = (entry![1] as { error: unknown }).error;
expect(logged).toBeInstanceOf(AggregateError);
expect(
(logged as AggregateError).errors.map((e: Error) => e.message),
).toEqual(["agent unavailable", "thread is archived"]);
consoleError.mockRestore();
});
it("posts a user-facing error when the agent run fails", async () => {
const error = new Error("agent unavailable");
const consoleError = vi
.spyOn(console, "error")
.mockImplementation(() => undefined);
const { adapter, channel } = makeChannel({
agent: new FakeAgent([
() => {
throw error;
},
]),
});
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "c1",
replyTarget: {},
userText: "hello",
platform: "slack",
actor: { id: "U1", kind: "human" },
});
expect(JSON.stringify(adapter.posted)).toMatch(/error/i);
expect(consoleError).toHaveBeenCalledWith(
"[channel] recoverable error",
expect.objectContaining({
error,
context: {
operation: "run_agent",
recovery: "posted_user_facing_error",
},
timestamp: expect.any(String),
}),
);
});
it("explains a lost Slack reply when event delivery times out", async () => {
const { adapter, channel } = makeChannel({
agent: new FakeAgent([
() => {
throw new Error("Timed out trying to durably deliver runner events");
},
]),
});
await channel.ɵruntime.start();
await adapter.getSink().onTurn({
conversationKey: "c1",
replyTarget: {},
userText: "hello",
platform: "slack",
actor: { id: "U1", kind: "human" },
});
expect(JSON.stringify(adapter.posted)).toMatch(/cut the live update/i);
});
it("posts a real JSON-stringified confirm_write interrupt card and returns immediately", async () => {
const agent = new FakeAgent([
(subscriber) => {
subscriber.onCustomEvent?.({
event: {
type: EventType.CUSTOM,
name: "on_interrupt",
value: JSON.stringify(confirmWriteEnvelope()),
},
} as never);
},
]);
const { adapter, channel } = makeChannel({
agent,
});
await channel.ɵruntime.start();
const turn = adapter.getSink().onTurn({
conversationKey: "c1",
replyTarget: {},
userText: "file this",
platform: "slack",
actor: { id: "U1", kind: "human" },
});
const result = await Promise.race([
Promise.resolve(turn).then(() => "returned"),
new Promise<string>((resolve) =>
setTimeout(() => resolve("blocked"), 100),
),