forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopilot-chat.ts
More file actions
388 lines (347 loc) · 11.7 KB
/
Copy pathcopilot-chat.ts
File metadata and controls
388 lines (347 loc) · 11.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
import {
Component,
input,
ChangeDetectionStrategy,
ViewEncapsulation,
signal,
effect,
ChangeDetectorRef,
Injector,
Type,
computed,
inject,
viewChild,
DestroyRef,
} from "@angular/core";
import { CopilotChatView } from "./copilot-chat-view";
import { CopilotChatAttachmentsDirective } from "./copilot-chat-attachments.directive";
import {
DEFAULT_AGENT_ID,
randomUUID,
type AttachmentsConfig,
} from "@copilotkit/shared";
import {
Message,
AbstractAgent,
HttpAgent,
AGUIConnectNotImplementedError,
} from "@ag-ui/client";
import type { Suggestion } from "@copilotkit/core";
import { injectAgentStore } from "../../agent";
import { CopilotKit } from "../../copilotkit";
import { ChatState } from "../../chat-state";
import { transcribeAudio } from "../../transcription";
import { COPILOT_CHAT_CONFIGURATION } from "../../chat-configuration";
import { connectActiveThread } from "../../active-thread-connector";
/**
* CopilotChat component - Angular equivalent of React's <CopilotChat>
* Provides a complete chat interface that wires an agent to the chat view
*
* @example
* ```html
* <copilot-chat [agentId]="'default'" [threadId]="'abc123'"></copilot-chat>
* ```
*/
@Component({
selector: "copilot-chat",
imports: [CopilotChatView, CopilotChatAttachmentsDirective],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
host: { "data-copilotkit": "", class: "cpk:block cpk:h-full cpk:min-h-0" },
template: `
<div
style="display: contents"
copilotChatAttachments
[config]="attachmentsConfig()"
>
<copilot-chat-view
[messages]="messages()"
[agentId]="resolvedAgentId()"
[autoScroll]="true"
[messageViewClass]="'cpk:w-full'"
[showCursor]="showCursor()"
[inputComponent]="inputComponent()"
[hasExplicitThreadId]="hasExplicitThreadId()"
>
</copilot-chat-view>
</div>
`,
providers: [
{
provide: ChatState,
useExisting: CopilotChat,
},
],
})
export class CopilotChat extends ChatState {
private readonly attachmentsDirective = viewChild(
CopilotChatAttachmentsDirective,
);
readonly inputValue = signal<string>("");
readonly agentId = input<string | undefined>();
readonly threadId = input<string | undefined>();
readonly inputComponent = input<Type<any> | undefined>();
readonly attachmentsConfig = input<AttachmentsConfig | undefined>(undefined, {
alias: "attachments",
});
/**
* Ambient chat configuration, when a {@link provideCopilotChatConfiguration}
* provider is in scope. Absent (`null`) for standalone
* `<copilot-chat [threadId]>` usage, which has no provider — resolved via the
* optional inject so the component does not throw without one.
*/
private readonly config = inject(COPILOT_CHAT_CONFIGURATION, {
optional: true,
});
protected readonly resolvedAgentId = computed(
() => this.agentId() ?? this.config?.agentId() ?? DEFAULT_AGENT_ID,
);
readonly agentStore = injectAgentStore(this.resolvedAgentId);
private readonly copilotKit = inject(CopilotKit);
readonly cdr = inject(ChangeDetectorRef);
readonly injector = inject(Injector);
private readonly destroyRef = inject(DestroyRef);
protected messages = computed(() => this.agentStore().messages());
protected isRunning = computed(() => this.agentStore().isRunning());
protected readonly hasExplicitThreadId =
this.config?.hasExplicitThreadId ??
computed(() => Boolean(this.threadId()));
protected readonly agentRef = computed(() => this.agentStore().agent);
protected readonly resolvedThreadId = computed(
() => this.threadId() || this.generatedThreadId,
);
override readonly attachmentsEnabled = computed(
() => this.attachmentsConfig()?.enabled ?? false,
);
override readonly attachmentsUploading = computed(() =>
this.attachments().some((attachment) => attachment.status === "uploading"),
);
protected showCursor = signal<boolean>(false);
private generatedThreadId: string = randomUUID();
constructor() {
super();
const suggestionsSubscription = this.copilotKit.core.subscribe({
onAgentsChanged: () => {
const agentId = this.resolvedAgentId();
this.syncSuggestionsFromCore(agentId);
if (this.copilotKit.core.getAgent(agentId)) {
this.copilotKit.reloadSuggestions(agentId);
}
},
onSuggestionsChanged: ({ agentId, suggestions }) => {
if (agentId !== this.resolvedAgentId()) {
return;
}
this.suggestions.set(suggestions);
this.suggestionsLoading.set(
this.copilotKit.core.getSuggestions(agentId).isLoading,
);
this.cdr.markForCheck();
},
onSuggestionsStartedLoading: ({ agentId }) => {
if (agentId !== this.resolvedAgentId()) {
return;
}
this.suggestionsLoading.set(true);
this.cdr.markForCheck();
},
onSuggestionsFinishedLoading: ({ agentId }) => {
if (agentId !== this.resolvedAgentId()) {
return;
}
this.syncSuggestionsFromCore(agentId);
},
onSuggestionsConfigChanged: () => {
const agentId = this.resolvedAgentId();
this.syncSuggestionsFromCore(agentId);
this.copilotKit.reloadSuggestions(agentId);
},
});
this.destroyRef.onDestroy(() => suggestionsSubscription.unsubscribe());
effect(() => {
const agentId = this.resolvedAgentId();
this.syncSuggestionsFromCore(agentId);
this.copilotKit.reloadSuggestions(agentId);
});
if (this.config) {
// A set `[threadId]` input seeds the ambient config so the input
// actually drives the active thread (not just the welcome flag). When
// the config is controlled by a host-provided `threadId` option,
// `setActiveThreadId` no-ops — so a controlled config wins over the
// input, matching React's prop-precedence. When `[threadId]` is unset,
// the effect does nothing and the config drives as before.
effect(() => {
const inputThreadId = this.threadId();
if (inputThreadId) {
this.config!.setActiveThreadId(inputThreadId, { explicit: true });
}
});
// Ambient configuration drives the active thread: the connector pins
// `agent.threadId` from the config's resolved thread signal and connects
// on explicit switches (or clears messages on a fresh thread).
//
// The connector receives the RAW `core.connectAgent` and owns the loading
// cursor + abort + detach lifecycle, matching the standalone
// `connectToAgent` path exactly: cursor on at connect start, off when the
// connect settles (guarded against a superseded run). Connect errors still
// surface via the AgentStore's run/error subscription, not here.
connectActiveThread(
this.config,
this.agentStore,
(params) => this.copilotKit.core.connectAgent(params),
{
onConnectStart: () => {
this.showCursor.set(true);
this.cdr.markForCheck();
},
onConnectSettle: () => {
this.showCursor.set(false);
this.cdr.markForCheck();
},
},
);
} else {
// Standalone `<copilot-chat [threadId]>` usage with no configuration
// provider: the active thread is input-driven exactly as before.
effect((onCleanup) => {
const agent = this.agentRef();
const threadId = this.resolvedThreadId();
agent.threadId = threadId;
if (!this.hasExplicitThreadId()) return;
let detached = false;
const abortController = new AbortController();
if (agent instanceof HttpAgent) {
agent.abortController = abortController;
}
void this.connectToAgent(agent, () => detached);
onCleanup(() => {
detached = true;
abortController.abort();
void agent.detachActiveRun().catch(() => {});
});
});
}
}
private async connectToAgent(
agent: AbstractAgent,
isDetached: () => boolean,
): Promise<void> {
this.showCursor.set(true);
this.cdr.markForCheck();
try {
await this.copilotKit.core.connectAgent({ agent });
} catch (error) {
if (isDetached()) return;
if (!(error instanceof AGUIConnectNotImplementedError)) {
console.error("Failed to connect to agent:", error);
}
} finally {
if (!isDetached()) {
this.showCursor.set(false);
this.cdr.markForCheck();
}
}
}
async submitInput(value: string): Promise<void> {
const agent = this.agentStore().agent;
if (!agent || !value.trim()) return;
if (this.attachmentsUploading()) {
console.error("[CopilotKit] Cannot send while attachments are uploading");
return;
}
const attachments = this.attachmentsDirective();
const readyAttachments = attachments?.consume() ?? [];
const userMessage: Message =
readyAttachments.length > 0
? ({
id: randomUUID(),
role: "user",
content: attachments!.buildContent(value, readyAttachments),
} as Message)
: {
id: randomUUID(),
role: "user",
content: value,
};
agent.addMessage(userMessage);
// Clear the input
this.inputValue.set("");
// Show cursor while processing
this.showCursor.set(true);
this.cdr.markForCheck();
// Run the agent via core so tools (and context, forwardedProps) are included
try {
await this.copilotKit.core.runAgent({ agent });
} catch (error) {
console.error("Agent run error:", error);
} finally {
this.showCursor.set(false);
this.cdr.markForCheck();
}
}
async selectSuggestion(
suggestion: Suggestion,
_index: number,
): Promise<void> {
const agent = this.agentStore().agent;
const message = suggestion.message.trim();
if (!agent || !message || suggestion.isLoading) return;
agent.addMessage({
id: randomUUID(),
role: "user",
content: message,
});
this.inputValue.set("");
this.showCursor.set(true);
this.cdr.markForCheck();
try {
await this.copilotKit.core.runAgent({ agent });
} catch (error) {
console.error("Agent run error:", error);
} finally {
this.showCursor.set(false);
this.cdr.markForCheck();
}
}
changeInput(value: string): void {
this.inputValue.set(value);
}
override async finishTranscription(audioBlob: Blob): Promise<void> {
this.isTranscribing.set(true);
this.cdr.markForCheck();
try {
const result = await transcribeAudio(this.copilotKit.core, audioBlob);
const text = result.text?.trim();
if (text) {
const previous = this.inputValue().trim();
this.inputValue.set(previous ? `${previous} ${text}` : text);
}
} catch (error) {
console.error("[CopilotKit] Transcription failed:", error);
} finally {
this.isTranscribing.set(false);
this.cdr.markForCheck();
}
}
private syncSuggestionsFromCore(agentId: string): void {
const result = this.copilotKit.core.getSuggestions(agentId);
this.suggestions.set(result.suggestions);
this.suggestionsLoading.set(result.isLoading);
this.cdr.markForCheck();
}
addFile(): void {
this.attachmentsDirective()?.openFilePicker();
}
removeAttachment(id: string): void {
this.attachmentsDirective()?.removeAttachment(id);
}
handleDragOver(event: DragEvent): void {
this.attachmentsDirective()?.onDragOver(event);
}
handleDragLeave(event: DragEvent): void {
this.attachmentsDirective()?.onDragLeave(event);
}
handleDrop(event: DragEvent): void {
void this.attachmentsDirective()?.onDrop(event);
}
}