forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.spec.ts
More file actions
401 lines (343 loc) · 11.1 KB
/
Copy pathagent.spec.ts
File metadata and controls
401 lines (343 loc) · 11.1 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
import {
ChangeDetectionStrategy,
Component,
Input,
signal,
} from "@angular/core";
import { TestBed } from "@angular/core/testing";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AbstractAgent } from "@ag-ui/client";
import type {
AgentSubscriber,
BaseEvent,
Message,
RunAgentInput,
State,
} from "@ag-ui/client";
import { Observable } from "rxjs";
import { AgentStore, injectAgentStore } from "./agent";
import { CopilotKit } from "./copilotkit";
import {
CopilotKitCore,
ProxiedCopilotRuntimeAgent,
CopilotKitCoreRuntimeConnectionStatus,
} from "@copilotkit/core";
/** Shape of the `core` property on the stub — derived from CopilotKitCore
* via Pick so the fields stay in sync with the real class. */
type StubCore = Pick<
CopilotKitCore,
| "runtimeUrl"
| "runtimeTransport"
| "runtimeConnectionStatus"
| "headers"
| "subscribeToAgentWithOptions"
> & {
agents?: Record<string, AbstractAgent>;
};
const DUMMY_RUN_INPUT: RunAgentInput = {
threadId: "",
runId: "",
state: {},
messages: [],
tools: [],
context: [],
forwardedProps: {},
};
function userMsg(id: string, content: string): Message {
return { id, role: "user" as const, content };
}
class MockAgent extends AbstractAgent {
unsubscribeCount = 0;
constructor(id: string) {
super();
this.agentId = id;
}
run(_input: RunAgentInput): Observable<BaseEvent> {
return new Observable();
}
override subscribe(subscriber: AgentSubscriber) {
const sub = super.subscribe(subscriber);
return {
unsubscribe: () => {
sub.unsubscribe();
this.unsubscribeCount += 1;
},
};
}
emitMessages(messages: Message[]) {
this.messages = messages;
for (const s of this.subscribers) {
s.onMessagesChanged?.({
messages: this.messages,
state: this.state,
agent: this,
});
}
}
/** Mirrors AbstractAgent.addMessage: mutate the messages array in place and
* notify with the SAME array reference (no reassignment). */
pushMessageInPlace(message: Message) {
this.messages.push(message);
for (const s of this.subscribers) {
s.onMessagesChanged?.({
messages: this.messages,
state: this.state,
agent: this,
});
}
}
emitState(state: State) {
this.state = state;
for (const s of this.subscribers) {
s.onStateChanged?.({
messages: this.messages,
state: this.state,
agent: this,
});
}
}
emitRunInitialized() {
for (const s of this.subscribers) {
s.onRunInitialized?.({
messages: this.messages,
state: this.state,
agent: this,
input: DUMMY_RUN_INPUT,
});
}
}
emitRunFinalized() {
for (const s of this.subscribers) {
s.onRunFinalized?.({
messages: this.messages,
state: this.state,
agent: this,
input: DUMMY_RUN_INPUT,
});
}
}
emitRunFailed() {
for (const s of this.subscribers) {
s.onRunFailed?.({
messages: this.messages,
state: this.state,
agent: this,
input: DUMMY_RUN_INPUT,
error: new Error("run failed"),
});
}
}
}
class CopilotKitStub {
readonly #agents = signal<Record<string, AbstractAgent>>({});
readonly #runtimeConnectionStatus =
signal<CopilotKitCoreRuntimeConnectionStatus>(
CopilotKitCoreRuntimeConnectionStatus.Disconnected,
);
readonly #runtimeUrl = signal<string | undefined>(undefined);
readonly #runtimeTransport = signal<"rest" | "single" | "auto">("auto");
readonly #headers = signal<Record<string, string>>({});
getAgent = vi.fn((id: string) => this.#agents()[id]);
agents = this.#agents.asReadonly();
runtimeConnectionStatus = this.#runtimeConnectionStatus.asReadonly();
runtimeUrl = this.#runtimeUrl.asReadonly();
runtimeTransport = this.#runtimeTransport.asReadonly();
headers = this.#headers.asReadonly();
#coreInstance = new CopilotKitCore({});
core: StubCore = {
runtimeUrl: undefined,
runtimeTransport: "auto",
runtimeConnectionStatus: CopilotKitCoreRuntimeConnectionStatus.Disconnected,
headers: {},
subscribeToAgentWithOptions:
this.#coreInstance.subscribeToAgentWithOptions.bind(this.#coreInstance),
};
setAgents(map: Record<string, AbstractAgent>) {
this.#agents.set(map);
this.core = { ...this.core, agents: map };
}
setRuntimeConnectionStatus(value: CopilotKitCoreRuntimeConnectionStatus) {
this.#runtimeConnectionStatus.set(value);
this.core = { ...this.core, runtimeConnectionStatus: value };
}
setRuntimeUrl(value: string | undefined) {
this.#runtimeUrl.set(value);
this.core = { ...this.core, runtimeUrl: value };
}
setHeaders(value: Record<string, string>) {
this.#headers.set(value);
this.core = { ...this.core, headers: value };
}
setRuntimeTransport(value: "rest" | "single" | "auto") {
this.#runtimeTransport.set(value);
this.core = { ...this.core, runtimeTransport: value };
}
}
describe("injectAgentStore", () => {
let copilotKitStub: CopilotKitStub;
beforeEach(() => {
TestBed.resetTestingModule();
copilotKitStub = new CopilotKitStub();
TestBed.configureTestingModule({
providers: [{ provide: CopilotKit, useValue: copilotKitStub }],
});
});
it("creates AgentStore instances that mirror agent events", () => {
const agent = new MockAgent("agent-1");
copilotKitStub.setAgents({ "agent-1": agent });
@Component({
standalone: true,
template: "",
})
class ConstantAgentHost {
store = injectAgentStore("agent-1");
}
const fixture = TestBed.createComponent(ConstantAgentHost);
fixture.detectChanges();
const store = fixture.componentInstance.store();
expect(store).toBeInstanceOf(AgentStore);
expect(store?.agent).toBe(agent);
agent.emitMessages([userMsg("1", "Hello")]);
expect(store?.messages()).toEqual([userMsg("1", "Hello")]);
agent.emitState({ loaded: true });
expect(store?.state()).toEqual({ loaded: true });
agent.emitRunInitialized();
expect(store?.isRunning()).toBe(true);
agent.emitRunFailed();
expect(store?.isRunning()).toBe(false);
});
it("disposes previous store when agent id changes and cleans up on destroy", () => {
const firstAgent = new MockAgent("agent-1");
const secondAgent = new MockAgent("agent-2");
copilotKitStub.setAgents({
"agent-1": firstAgent,
"agent-2": secondAgent,
});
@Component({
standalone: true,
template: "",
})
class HostComponent {
agentId = signal<string | undefined>("agent-1");
store = injectAgentStore(this.agentId);
}
const fixture = TestBed.createComponent(HostComponent);
fixture.detectChanges();
expect(fixture.componentInstance.store()?.agent).toBe(firstAgent);
fixture.componentInstance.agentId.set("agent-2");
copilotKitStub.setAgents({
"agent-1": firstAgent,
"agent-2": secondAgent,
});
fixture.detectChanges();
expect(fixture.componentInstance.store()?.agent).toBe(secondAgent);
expect(firstAgent.unsubscribeCount).toBe(1);
fixture.destroy();
expect(secondAgent.unsubscribeCount).toBe(1);
});
it("returns a proxied AgentStore while runtime is connecting", () => {
copilotKitStub.setAgents({});
copilotKitStub.setRuntimeUrl("https://runtime.local");
copilotKitStub.setHeaders({ "x-test": "1" });
copilotKitStub.setRuntimeConnectionStatus(
CopilotKitCoreRuntimeConnectionStatus.Connecting,
);
@Component({
standalone: true,
template: "",
})
class MissingAgentHost {
store = injectAgentStore("missing");
}
const fixture = TestBed.createComponent(MissingAgentHost);
fixture.detectChanges();
const store = fixture.componentInstance.store();
expect(store).toBeInstanceOf(AgentStore);
const proxied = store.agent;
expect(proxied).toBeInstanceOf(ProxiedCopilotRuntimeAgent);
// Single narrowing after the instanceof assertion above
const proxiedAgent = proxied as ProxiedCopilotRuntimeAgent;
expect(proxiedAgent.agentId).toBe("missing");
expect(proxiedAgent.headers).toEqual({ "x-test": "1" });
});
it("throws when agent cannot be resolved after runtime sync", () => {
copilotKitStub.setAgents({});
copilotKitStub.setRuntimeUrl("https://runtime.local");
copilotKitStub.setRuntimeConnectionStatus(
CopilotKitCoreRuntimeConnectionStatus.Connected,
);
@Component({
standalone: true,
template: "",
})
class MissingAgentHost {
store = injectAgentStore("missing");
}
const fixture = TestBed.createComponent(MissingAgentHost);
fixture.detectChanges();
expect(() => fixture.componentInstance.store()).toThrowError(
/injectAgentStore: Agent 'missing' not found after runtime sync/,
);
});
// Regression: issue #5416. AbstractAgent.addMessage mutates its messages
// array in place and notifies with the same reference; the store must not
// forward that live reference, or the signal's Object.is check makes set()
// a no-op and OnPush views never re-render until the run finishes.
it("exposes a fresh array reference, not the agent's live messages array", () => {
const agent = new MockAgent("agent-1");
copilotKitStub.setAgents({ "agent-1": agent });
@Component({
standalone: true,
template: "",
})
class Host {
store = injectAgentStore("agent-1");
}
const fixture = TestBed.createComponent(Host);
fixture.detectChanges();
const store = fixture.componentInstance.store();
agent.pushMessageInPlace(userMsg("1", "Hello"));
expect(store.messages()).toEqual([userMsg("1", "Hello")]);
expect(store.messages()).not.toBe(agent.messages);
});
it("re-renders an OnPush view when messages are mutated in place", () => {
const agent = new MockAgent("agent-1");
copilotKitStub.setAgents({ "agent-1": agent });
@Component({
selector: "message-count",
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
{{ store.messages().length }}
`,
})
class MessageCount {
@Input({ required: true }) store!: AgentStore;
}
@Component({
standalone: true,
imports: [MessageCount],
template: `
<message-count [store]="store()" />
`,
})
class Host {
store = injectAgentStore("agent-1");
}
const fixture = TestBed.createComponent(Host);
fixture.detectChanges();
const rendered = () => fixture.nativeElement.textContent.trim();
expect(rendered()).toBe("0");
// First in-place push: the signal's reference differs from its initial
// value, so this notifies even with the bug present.
agent.pushMessageInPlace(userMsg("1", "Hello"));
fixture.detectChanges();
expect(rendered()).toBe("1");
// Second in-place push reuses the array reference the signal now holds.
// Without the shallow copy this is an Object.is no-op: the signal never
// notifies, the OnPush child stays clean, and the count stays at "1".
agent.pushMessageInPlace(userMsg("2", "World"));
fixture.detectChanges();
expect(rendered()).toBe("2");
});
});