1import type {
2  AttachmentsConfig,
3  FrontendToolConfig,
4  HumanInTheLoopConfig,
5  RenderToolCallConfig,
6} from "@copilotkit/angular";
7import {
8  injectAgentStore,
9  registerFrontendTool,
10  registerHumanInTheLoop,
11  registerRenderActivityMessage,
12  registerRenderToolCall,
13} from "@copilotkit/angular";
14import type { Type } from "@angular/core";
15import {
16  ChangeDetectionStrategy,
17  Component,
18  computed,
19  signal,
20} from "@angular/core";
21import { mcpAppsActivityRendererConfig } from "@copilotkit/angular/mcp-apps";
22import { z } from "zod";
23
24import { agentIdForCurrentIntegration } from "../../feature-agent";
25import { FeatureHeaderComponent } from "../feature-header.component";
26import { SHOWCASE_MCP_APPS_PROVIDER } from "../generated-ui/mcp-apps-provider";
27import { ShowcaseChatHostComponent } from "../showcase-chat-host.component";
28import {
29  BarChartCard,
30  BeautifulToolReasoningCard,
31  MeetingTimePickerCard,
32  PieChartCard,
33} from "./beautiful-chat-cards";
34import { toggleDocumentTheme } from "./beautiful-chat-model";
35import type { BeautifulTodo } from "./beautiful-todo-canvas";
36import {
37  BeautifulTodoCanvas,
38  readBeautifulTodos,
39} from "./beautiful-todo-canvas";
40
41type ToolArgs = Record<string, unknown>;
42
43const ATTACHMENTS: AttachmentsConfig = { enabled: true };
44const chartParameters = z.object({
45  title: z.string(),
46  description: z.string(),
47  data: z.array(z.object({ label: z.string(), value: z.number() })),
48});
49
50@Component({
51  selector: "showcase-beautiful-chat-feature",
52  imports: [
53    BeautifulTodoCanvas,
54    FeatureHeaderComponent,
55    ShowcaseChatHostComponent,
56  ],
57  providers: [SHOWCASE_MCP_APPS_PROVIDER],
58  changeDetection: ChangeDetectionStrategy.OnPush,
59  host: { class: "feature-page" },
60  template: `
61    <showcase-feature-header />
62    <main class="beautiful-page" [class.app-mode]="mode() === 'app'">
63      <nav class="mode-toggle" aria-label="Beautiful Chat view">
64        <button
65          type="button"
66          [attr.aria-pressed]="mode() === 'chat'"
67          (click)="mode.set('chat')"
68        >
69          Chat
70        </button>
71        <button
72          type="button"
73          [attr.aria-pressed]="mode() === 'app'"
74          (click)="mode.set('app')"
75        >
76          App
77        </button>
78      </nav>
79      <section class="chat-pane" aria-label="CopilotKit assistant">
80        <header class="brand">
81          <strong>CopilotKit</strong><span aria-hidden="true">✦</span>
82        </header>
83        <div class="chat-surface">
84          <showcase-chat-host [attachments]="attachments" />
85        </div>
86      </section>
87      <section class="app-pane" aria-label="Shared-state task manager">
88        <showcase-beautiful-todo-canvas
89          [todos]="todos()"
90          [isRunning]="isRunning()"
91          (todosChange)="setTodos($event)"
92        />
93      </section>
94    </main>
95  `,
96  styles: `
97    .beautiful-page {
98      position: relative;
99      display: grid;
100      min-height: 0;
101      grid-template-columns: minmax(0, 1fr) 0;
102      overflow: hidden;
103      color: light-dark(#14213d, #fafafa);
104      background: light-dark(#fff, #0a0a0a);
105      transition: grid-template-columns 180ms ease;
106    }
107    .beautiful-page.app-mode {
108      grid-template-columns: minmax(20rem, 1fr) minmax(0, 2fr);
109    }
110    .mode-toggle {
111      position: absolute;
112      z-index: 4;
113      top: 0.75rem;
114      right: 0.75rem;
115      display: flex;
116      gap: 0.15rem;
117      padding: 0.2rem;
118      border: 1px solid light-dark(#d8e0ea, #303136);
119      border-radius: 999px;
120      background: light-dark(#eef2f7, #242529);
121    }
122    .mode-toggle button {
123      padding: 0.4rem 0.85rem;
124      border: 0;
125      border-radius: 999px;
126      color: light-dark(#52637a, #adadb2);
127      background: transparent;
128      font: inherit;
129      font-size: 0.8rem;
130      font-weight: 650;
131      cursor: pointer;
132    }
133    .mode-toggle button[aria-pressed="true"] {
134      color: light-dark(#14213d, #fafafa);
135      background: light-dark(#fff, #303136);
136      box-shadow: 0 1px 4px #94a3b855;
137    }
138    .mode-toggle button:focus-visible {
139      outline: 3px solid #91a7ff;
140      outline-offset: 2px;
141    }
142    .chat-pane {
143      display: grid;
144      min-width: 0;
145      min-height: 0;
146      grid-template-rows: auto minmax(0, 1fr);
147    }
148    .brand {
149      display: flex;
150      align-items: center;
151      gap: 0.4rem;
152      padding: 1rem 1.25rem 0.5rem;
153      font-size: 1.35rem;
154    }
155    .brand span {
156      color: #4263eb;
157    }
158    .chat-surface {
159      min-height: 0;
160      overflow: hidden;
161    }
162    .app-pane {
163      min-width: 0;
164      min-height: 0;
165      overflow: auto;
166      border-left: 1px solid light-dark(#d8e0ea, #303136);
167    }
168    @media (prefers-reduced-motion: reduce) {
169      .beautiful-page {
170        transition: none;
171      }
172    }
173    @media (max-width: 64rem) {
174      .beautiful-page.app-mode {
175        grid-template-columns: 0 minmax(0, 1fr);
176      }
177      .beautiful-page.app-mode .chat-pane {
178        visibility: hidden;
179      }
180      .app-pane {
181        border-left: 0;
182      }
183    }
184  `,
185})
186export class BeautifulChatFeatureComponent {
187  protected readonly mode = signal<"chat" | "app">("chat");
188  protected readonly attachments = ATTACHMENTS;
189  private readonly agentId = agentIdForCurrentIntegration("beautiful-chat");
190  private readonly agentStore = injectAgentStore(this.agentId);
191  protected readonly todos = computed(() =>
192    readBeautifulTodos(this.agentStore().state()),
193  );
194  protected readonly isRunning = computed(() => this.agentStore().isRunning());
195
196  constructor() {
197    registerRenderActivityMessage(mcpAppsActivityRendererConfig);
198    this.registerChart("pieChart", PieChartCard);
199    this.registerChart("barChart", BarChartCard);
200    this.registerMeetingPicker();
201    this.registerThemeTool();
202    this.registerModeTool("enableAppMode", "app");
203    this.registerModeTool("enableChatMode", "chat");
204    registerRenderToolCall({
205      name: "*",
206      args: z.record(z.unknown()),
207      component: asRenderer(BeautifulToolReasoningCard),
208    });
209  }
210
211  /** Persist an immutable task list into the connected agent state. */
212  protected setTodos(todos: BeautifulTodo[]): void {
213    this.agentStore().agent.setState({ todos });
214  }
215
216  /** Register one controlled chart as a renderable frontend tool. */
217  private registerChart(
218    name: "pieChart" | "barChart",
219    component: Type<unknown>,
220  ): void {
221    registerFrontendTool({
222      name,
223      description: `Render a controlled ${name === "pieChart" ? "pie" : "bar"} chart.`,
224      parameters: chartParameters,
225      component: asFrontendRenderer(component),
226      handler: async (args) => args,
227    });
228  }
229
230  /** Register the scheduling decision as a human-in-the-loop tool. */
231  private registerMeetingPicker(): void {
232    const config: HumanInTheLoopConfig<ToolArgs> = {
233      name: "scheduleTime",
234      description: "Ask the user to choose a meeting time.",
235      parameters: z.object({
236        reasonForScheduling: z.string(),
237        meetingDuration: z.number(),
238      }),
239      component: asHitlRenderer(MeetingTimePickerCard),
240    };
241    registerHumanInTheLoop(config);
242  }
243
244  /** Register the browser-only theme mutation tool. */
245  private registerThemeTool(): void {
246    registerFrontendTool({
247      name: "toggleTheme",
248      description: "Toggle the showcase between light and dark themes.",
249      parameters: z.object({}),
250      followUp: true,
251      handler: async () => ({
252        theme: toggleDocumentTheme(globalThis.document?.documentElement),
253      }),
254    });
255  }
256
257  /** Register one frontend tool that switches the responsive workspace mode. */
258  private registerModeTool(name: string, mode: "chat" | "app"): void {
259    registerFrontendTool({
260      name,
261      description: `Enable ${mode} mode.`,
262      parameters: z.object({}),
263      followUp: false,
264      handler: async () => {
265        this.mode.set(mode);
266        return { mode };
267      },
268    });
269  }
270}
271
272/** Isolate the source Angular-major type brand at the dynamic renderer edge. */
273function asRenderer(
274  component: Type<unknown>,
275): RenderToolCallConfig<ToolArgs>["component"] {
276  return component as unknown as RenderToolCallConfig<ToolArgs>["component"];
277}
278
279/** Isolate the source Angular-major type brand for frontend renderers. */
280function asFrontendRenderer(
281  component: Type<unknown>,
282): NonNullable<FrontendToolConfig<ToolArgs>["component"]> {
283  return component as unknown as NonNullable<
284    FrontendToolConfig<ToolArgs>["component"]
285  >;
286}
287
288/** Isolate the source Angular-major type brand for HITL renderers. */
289function asHitlRenderer(
290  component: Type<unknown>,
291): HumanInTheLoopConfig<ToolArgs>["component"] {
292  return component as unknown as HumanInTheLoopConfig<ToolArgs>["component"];
293}
294
7fdfe25e2
CopilotKit Showcase