cortena-ui 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +149 -1
  3. package/dist/a2ui/views.js +2 -2
  4. package/dist/agent-chat/a2ui-block.d.ts +60 -0
  5. package/dist/agent-chat/a2ui-block.js +69 -0
  6. package/dist/agent-chat/a2ui-block.js.map +1 -0
  7. package/dist/agent-chat/agui-client.d.ts +40 -0
  8. package/dist/agent-chat/agui-client.js +251 -0
  9. package/dist/agent-chat/agui-client.js.map +1 -0
  10. package/dist/agent-chat/bridge.d.ts +109 -0
  11. package/dist/agent-chat/bridge.js +349 -0
  12. package/dist/agent-chat/bridge.js.map +1 -0
  13. package/dist/agent-chat/session.d.ts +58 -0
  14. package/dist/agent-chat/session.js +249 -0
  15. package/dist/agent-chat/session.js.map +1 -0
  16. package/dist/agent-chat/store.d.ts +67 -0
  17. package/dist/agent-chat/store.js +548 -0
  18. package/dist/agent-chat/store.js.map +1 -0
  19. package/dist/agent-chat/types.d.ts +187 -0
  20. package/dist/agent-chat/types.js +17 -0
  21. package/dist/agent-chat/types.js.map +1 -0
  22. package/dist/agent-chat.d.ts +10 -0
  23. package/dist/agent-chat.js +10 -0
  24. package/dist/components/admin-permissions/admin-permissions.d.ts +66 -0
  25. package/dist/components/admin-permissions/admin-permissions.js +101 -0
  26. package/dist/components/admin-permissions/admin-permissions.js.map +1 -0
  27. package/dist/components/admin-permissions/context.d.ts +70 -0
  28. package/dist/components/admin-permissions/context.js +258 -0
  29. package/dist/components/admin-permissions/context.js.map +1 -0
  30. package/dist/components/admin-permissions/index.d.ts +10 -0
  31. package/dist/components/admin-permissions/licence.d.ts +15 -0
  32. package/dist/components/admin-permissions/licence.js +78 -0
  33. package/dist/components/admin-permissions/licence.js.map +1 -0
  34. package/dist/components/admin-permissions/matrix.d.ts +20 -0
  35. package/dist/components/admin-permissions/matrix.js +191 -0
  36. package/dist/components/admin-permissions/matrix.js.map +1 -0
  37. package/dist/components/admin-permissions/members.d.ts +18 -0
  38. package/dist/components/admin-permissions/members.js +185 -0
  39. package/dist/components/admin-permissions/members.js.map +1 -0
  40. package/dist/components/admin-permissions/role-assignment.d.ts +35 -0
  41. package/dist/components/admin-permissions/role-assignment.js +174 -0
  42. package/dist/components/admin-permissions/role-assignment.js.map +1 -0
  43. package/dist/components/admin-permissions/roles.d.ts +25 -0
  44. package/dist/components/admin-permissions/roles.js +168 -0
  45. package/dist/components/admin-permissions/roles.js.map +1 -0
  46. package/dist/components/admin-permissions/types.d.ts +152 -0
  47. package/dist/components/admin-permissions/types.js +63 -0
  48. package/dist/components/admin-permissions/types.js.map +1 -0
  49. package/dist/components/agent-chat-popup.d.ts +29 -0
  50. package/dist/components/agent-chat-popup.js +188 -0
  51. package/dist/components/agent-chat-popup.js.map +1 -0
  52. package/dist/components/agent-chat.d.ts +143 -0
  53. package/dist/components/agent-chat.js +578 -0
  54. package/dist/components/agent-chat.js.map +1 -0
  55. package/dist/components/app-shell.d.ts +126 -0
  56. package/dist/components/app-shell.js +297 -0
  57. package/dist/components/app-shell.js.map +1 -0
  58. package/dist/components/badge.d.ts +1 -1
  59. package/dist/components/button-link.js +1 -1
  60. package/dist/components/button.d.ts +2 -2
  61. package/dist/components/checkbox.d.ts +1 -1
  62. package/dist/components/combobox.d.ts +1 -1
  63. package/dist/components/combobox.js +1 -1
  64. package/dist/components/consent-screen.d.ts +65 -0
  65. package/dist/components/consent-screen.js +123 -0
  66. package/dist/components/consent-screen.js.map +1 -0
  67. package/dist/components/data-table/data-table.d.ts +15 -1
  68. package/dist/components/data-table/data-table.js +18 -4
  69. package/dist/components/data-table/data-table.js.map +1 -1
  70. package/dist/components/data-table/index.d.ts +4 -4
  71. package/dist/components/data-table/parts.d.ts +27 -3
  72. package/dist/components/data-table/parts.js +175 -55
  73. package/dist/components/data-table/parts.js.map +1 -1
  74. package/dist/components/data-table/types.d.ts +61 -0
  75. package/dist/components/data-table/use-data-table.js +91 -6
  76. package/dist/components/data-table/use-data-table.js.map +1 -1
  77. package/dist/components/data-table/use-server-source.js +119 -28
  78. package/dist/components/data-table/use-server-source.js.map +1 -1
  79. package/dist/components/help-panel.d.ts +131 -0
  80. package/dist/components/help-panel.js +545 -0
  81. package/dist/components/help-panel.js.map +1 -0
  82. package/dist/components/login-screen.d.ts +127 -0
  83. package/dist/components/login-screen.js +339 -0
  84. package/dist/components/login-screen.js.map +1 -0
  85. package/dist/components/session-guard.d.ts +268 -0
  86. package/dist/components/session-guard.js +632 -0
  87. package/dist/components/session-guard.js.map +1 -0
  88. package/dist/components/toast.d.ts +1 -1
  89. package/dist/core.d.ts +5 -1
  90. package/dist/core.js +11 -7
  91. package/dist/data-table.d.ts +13 -4
  92. package/dist/data-table.js +10 -2
  93. package/dist/hooks/use-cortena-theme.js +49 -3
  94. package/dist/hooks/use-cortena-theme.js.map +1 -1
  95. package/dist/index.d.ts +17 -4
  96. package/dist/index.js +21 -8
  97. package/dist/markdown.d.ts +2 -1
  98. package/dist/markdown.js +2 -1
  99. package/package.json +16 -4
  100. package/src/agent-chat/a2ui-block.ts +118 -0
  101. package/src/agent-chat/agui-client.ts +405 -0
  102. package/src/agent-chat/bridge.ts +433 -0
  103. package/src/agent-chat/session.ts +392 -0
  104. package/src/agent-chat/store.ts +738 -0
  105. package/src/agent-chat/types.ts +213 -0
  106. package/src/components/admin-permissions/admin-permissions.tsx +130 -0
  107. package/src/components/admin-permissions/context.tsx +376 -0
  108. package/src/components/admin-permissions/index.tsx +32 -0
  109. package/src/components/admin-permissions/licence.tsx +84 -0
  110. package/src/components/admin-permissions/matrix.tsx +257 -0
  111. package/src/components/admin-permissions/members.tsx +204 -0
  112. package/src/components/admin-permissions/role-assignment.tsx +239 -0
  113. package/src/components/admin-permissions/roles.tsx +169 -0
  114. package/src/components/admin-permissions/types.ts +231 -0
  115. package/src/components/agent-chat-popup.tsx +289 -0
  116. package/src/components/agent-chat.tsx +843 -0
  117. package/src/components/app-shell.tsx +502 -0
  118. package/src/components/consent-screen.tsx +239 -0
  119. package/src/components/data-table/data-table.tsx +36 -0
  120. package/src/components/data-table/index.tsx +6 -1
  121. package/src/components/data-table/parts.tsx +223 -47
  122. package/src/components/data-table/types.ts +68 -0
  123. package/src/components/data-table/use-data-table.ts +152 -4
  124. package/src/components/data-table/use-server-source.ts +150 -12
  125. package/src/components/help-panel.tsx +765 -0
  126. package/src/components/login-screen.tsx +479 -0
  127. package/src/components/session-guard.tsx +1071 -0
  128. package/src/entries/agent-chat.ts +113 -0
  129. package/src/entries/core.ts +8 -0
  130. package/src/entries/data-table.ts +41 -0
  131. package/src/entries/markdown.ts +25 -0
  132. package/src/hooks/use-cortena-theme.ts +63 -4
  133. package/src/index.ts +6 -0
@@ -0,0 +1,843 @@
1
+ "use client";
2
+
3
+ /**
4
+ * AgentChat — the chat surface an extension's own agent runs in.
5
+ *
6
+ * §17 of how-to-create-a-cortena-extension, audit rule P-25. Moved here from
7
+ * `cortenaweb/components/chat/**` so there is one chat and not two: a cut-down
8
+ * widget diverges on approvals, A2UI and MCP Apps within one release, and every
9
+ * fix then has to be made twice. cortenaweb adopts this component as a
10
+ * follow-up; until then the two are kept in step by hand.
11
+ *
12
+ * Everything comes from the `AgentChatClient` prop — nothing here knows about
13
+ * HTTP, AG-UI or a store — which is what lets `test/agent-chat.test.tsx` drive
14
+ * the whole surface from a fake that replays scripted event sequences.
15
+ *
16
+ * Not in this package, on purpose: the MCP App frame. Rendering an extension's
17
+ * own screen means a sandboxed iframe, a `srcdoc` CSP, a JSON-RPC postMessage
18
+ * bridge and a `tools/invoke` proxy holding a credential — a host concern, not
19
+ * a component one. `renderToolCall` is the seam: return a node for a tool call
20
+ * and it replaces the card, return nothing and the default card is drawn.
21
+ */
22
+
23
+ import {
24
+ ChevronDown,
25
+ ChevronRight,
26
+ MessageSquarePlus,
27
+ Send,
28
+ ShieldCheck,
29
+ ShieldX,
30
+ Sparkles,
31
+ Square,
32
+ } from "lucide-react";
33
+ import * as React from "react";
34
+ import { A2UIRenderer } from "@/a2ui/renderer";
35
+ import { A2UIErrorCard } from "@/a2ui/views";
36
+ import type { A2UIAction, A2UIMessage } from "@/a2ui/message";
37
+ import { Badge } from "@/components/badge";
38
+ import { Button } from "@/components/button";
39
+ import { ErrorBanner } from "@/components/error-banner";
40
+ import { Markdown } from "@/components/markdown";
41
+ import { Spinner } from "@/components/spinner";
42
+ import { Textarea } from "@/components/textarea";
43
+ import { isHiddenMessage } from "@/agent-chat/session";
44
+ import { type AgentToolEntry, useAgentChat } from "@/agent-chat/store";
45
+ import type {
46
+ AgentApprovalRequest,
47
+ AgentChatClient,
48
+ AgentChatMessage,
49
+ AgentSession,
50
+ } from "@/agent-chat/types";
51
+ import { sessionTitle } from "@/agent-chat/types";
52
+ import type { A2UIChatBlock } from "@/agent-chat/a2ui-block";
53
+ import { cn } from "@/lib/cn";
54
+
55
+ /* ── stick to bottom ─────────────────────────────────────────────────────── */
56
+
57
+ /**
58
+ * Should the list jump back to the bottom after its content grew?
59
+ *
60
+ * Judged against the height BEFORE the growth. Measuring afterwards asks "is
61
+ * the newest content already visible", which is false by construction for any
62
+ * append taller than the threshold — a paragraph, a code block, an image — so
63
+ * the re-pin skipped exactly when it was needed.
64
+ */
65
+ export function shouldStickToBottom(params: {
66
+ prevScrollHeight: number;
67
+ scrollTop: number;
68
+ clientHeight: number;
69
+ threshold?: number;
70
+ }): boolean {
71
+ const { prevScrollHeight, scrollTop, clientHeight, threshold = 150 } = params;
72
+ if (prevScrollHeight <= 0) {
73
+ return true;
74
+ }
75
+ return prevScrollHeight - scrollTop - clientHeight < threshold;
76
+ }
77
+
78
+ /* ── thinking ────────────────────────────────────────────────────────────── */
79
+
80
+ export interface AgentThinkingProps {
81
+ text: string;
82
+ /** Open by default while the turn is live, collapsed once it is finished. */
83
+ defaultOpen?: boolean;
84
+ streaming?: boolean;
85
+ }
86
+
87
+ function AgentThinking({ text, defaultOpen, streaming }: AgentThinkingProps) {
88
+ const [open, setOpen] = React.useState(defaultOpen ?? false);
89
+ if (!text) {
90
+ return null;
91
+ }
92
+ return (
93
+ <div data-slot="agent-chat-thinking" className="mt-1">
94
+ <button
95
+ type="button"
96
+ aria-expanded={open}
97
+ onClick={() => setOpen((v) => !v)}
98
+ className={cn(
99
+ "inline-flex items-center gap-1 rounded-[var(--ds-radius-sm)] px-1 py-0.5",
100
+ "text-[length:var(--ds-text-caption)] text-[color:var(--ds-muted-foreground)]",
101
+ "transition-colors duration-[var(--ds-duration-fast)] hover:text-[color:var(--ds-foreground)]",
102
+ )}
103
+ >
104
+ {open ? <ChevronDown className="size-3" aria-hidden /> : <ChevronRight className="size-3" aria-hidden />}
105
+ {streaming ? "Thinking…" : "Chain of thought"}
106
+ </button>
107
+ {open ? (
108
+ <div
109
+ data-slot="agent-chat-thinking-body"
110
+ className={cn(
111
+ "mt-1 max-h-64 overflow-auto rounded-[var(--ds-radius-sm)] border border-[var(--ds-border-subtle)]",
112
+ "bg-[var(--ds-muted)] px-3 py-2 whitespace-pre-wrap",
113
+ "text-[length:var(--ds-text-caption)] text-[color:var(--ds-muted-foreground)]",
114
+ )}
115
+ >
116
+ {text}
117
+ </div>
118
+ ) : null}
119
+ </div>
120
+ );
121
+ }
122
+
123
+ /* ── A2UI blocks ─────────────────────────────────────────────────────────── */
124
+
125
+ export interface AgentA2UIBlocksProps {
126
+ blocks: readonly A2UIChatBlock[] | undefined;
127
+ /** Set on the streaming bubble: actions are disabled while the turn is live. */
128
+ streaming?: boolean;
129
+ onAction?: (action: A2UIAction) => void;
130
+ }
131
+
132
+ /**
133
+ * Every block of one message, in arrival order.
134
+ *
135
+ * A block carrying a transport `error` — an unclosed fence, a body that did not
136
+ * parse — gets an error card rather than being dropped. A block that is merely
137
+ * malformed inside is the renderer's error to draw, and it draws the parts that
138
+ * were fine.
139
+ */
140
+ function AgentA2UIBlocks({ blocks, streaming, onAction }: AgentA2UIBlocksProps) {
141
+ if (!blocks || blocks.length === 0) {
142
+ return null;
143
+ }
144
+ return (
145
+ <div className="mt-2 flex flex-col gap-3" data-slot="agent-chat-a2ui">
146
+ {blocks.map((block, index) => (
147
+ <div key={`${block.surfaceId}:${index}`}>
148
+ {block.error ? (
149
+ <A2UIErrorCard title="The agent's UI did not arrive complete" detail={block.error} />
150
+ ) : null}
151
+ {block.messages.length > 0 ? (
152
+ <A2UIRenderer
153
+ // The payload stays `unknown[]`: it is the agent's, and only the
154
+ // renderer validates it. Every node goes through the catalogue's
155
+ // schema before it is drawn.
156
+ message={block.messages as A2UIMessage[]}
157
+ // A surface still streaming must not fire actions at the agent
158
+ // from a half-built form, so it is read-only until final.
159
+ {...(streaming || !onAction ? {} : { onAction })}
160
+ />
161
+ ) : null}
162
+ </div>
163
+ ))}
164
+ </div>
165
+ );
166
+ }
167
+
168
+ /* ── bubbles ─────────────────────────────────────────────────────────────── */
169
+
170
+ function AssistantAvatar() {
171
+ return (
172
+ <span
173
+ data-slot="agent-chat-avatar"
174
+ aria-hidden
175
+ className={cn(
176
+ "grid size-7 shrink-0 place-items-center rounded-[var(--ds-radius-sm)]",
177
+ "border border-[var(--ds-ring)] bg-[var(--ds-primary-soft)] text-[color:var(--ds-primary)]",
178
+ )}
179
+ >
180
+ <Sparkles className="size-3.5" aria-hidden />
181
+ </span>
182
+ );
183
+ }
184
+
185
+ export interface AgentMessageBubbleProps {
186
+ message: AgentChatMessage;
187
+ agentName: string;
188
+ /**
189
+ * True while a run is live. Every A2UI surface in the transcript goes
190
+ * read-only, not just the one being drawn: an earlier surface is still a
191
+ * form wired to `sendAction`, and pressing it mid-run starts a second
192
+ * concurrent turn on the same session.
193
+ */
194
+ streaming?: boolean;
195
+ onAction?: (action: A2UIAction) => void;
196
+ }
197
+
198
+ function AgentMessageBubble({ message, agentName, streaming, onAction }: AgentMessageBubbleProps) {
199
+ if (isHiddenMessage(message)) {
200
+ return null;
201
+ }
202
+ if (message.isError) {
203
+ return (
204
+ <div data-slot="agent-chat-message" data-role="error">
205
+ <ErrorBanner message={message.text} />
206
+ </div>
207
+ );
208
+ }
209
+ if (message.role === "user") {
210
+ return (
211
+ <div data-slot="agent-chat-message" data-role="user" className="flex w-full justify-end">
212
+ <div
213
+ className={cn(
214
+ "max-w-[85%] rounded-[var(--ds-radius-lg)] border border-[var(--ds-border-subtle)]",
215
+ "bg-[var(--ds-popover)] px-3.5 py-2 text-[color:var(--ds-foreground)]",
216
+ )}
217
+ >
218
+ <Markdown compact>{message.text}</Markdown>
219
+ </div>
220
+ </div>
221
+ );
222
+ }
223
+ return (
224
+ <div data-slot="agent-chat-message" data-role="assistant" className="flex w-full gap-3">
225
+ <AssistantAvatar />
226
+ <div className="min-w-0 flex-1">
227
+ <span
228
+ className={cn(
229
+ "text-[length:var(--ds-text-caption)] font-semibold",
230
+ "text-[color:var(--ds-foreground)]",
231
+ )}
232
+ >
233
+ {agentName}
234
+ </span>
235
+ <AgentThinking text={message.thinkingText ?? ""} />
236
+ {message.text ? (
237
+ <div className="mt-1">
238
+ <Markdown compact>{message.text}</Markdown>
239
+ </div>
240
+ ) : null}
241
+ <AgentA2UIBlocks
242
+ blocks={message.a2ui}
243
+ {...(streaming ? { streaming } : {})}
244
+ {...(onAction ? { onAction } : {})}
245
+ />
246
+ </div>
247
+ </div>
248
+ );
249
+ }
250
+
251
+ export interface AgentStreamingBubbleProps {
252
+ agentName: string;
253
+ text: string;
254
+ thinkingText: string;
255
+ a2ui: readonly A2UIChatBlock[];
256
+ }
257
+
258
+ /**
259
+ * The assistant bubble while a turn is live.
260
+ *
261
+ * The filter chain is deliberately not applied: streaming text is
262
+ * agent-authored prose in progress, and the filters are about finished
263
+ * messages. Markdown is not processed either — partially arrived source
264
+ * (`**bo`) looks worse than its raw form — so the streaming view is plain text
265
+ * under `whitespace-pre-wrap` and `Markdown` takes over on `final`.
266
+ */
267
+ function AgentStreamingBubble({ agentName, text, thinkingText, a2ui }: AgentStreamingBubbleProps) {
268
+ return (
269
+ <div data-slot="agent-chat-streaming" className="flex w-full gap-3">
270
+ <AssistantAvatar />
271
+ <div className="min-w-0 flex-1">
272
+ <span
273
+ className={cn(
274
+ "text-[length:var(--ds-text-caption)] font-semibold",
275
+ "text-[color:var(--ds-foreground)]",
276
+ )}
277
+ >
278
+ {agentName}
279
+ </span>
280
+ {thinkingText ? <AgentThinking text={thinkingText} defaultOpen streaming /> : null}
281
+ {text ? (
282
+ <div
283
+ data-slot="agent-chat-streaming-text"
284
+ className="mt-1 break-words whitespace-pre-wrap text-[color:var(--ds-foreground)]"
285
+ >
286
+ {text}
287
+ </div>
288
+ ) : null}
289
+ <AgentA2UIBlocks blocks={a2ui} streaming />
290
+ </div>
291
+ </div>
292
+ );
293
+ }
294
+
295
+ /* ── tool cards ──────────────────────────────────────────────────────────── */
296
+
297
+ /** A `ui://` resource in a tool result is an MCP App: the extension's own screen. */
298
+ export function readMcpAppUri(output: unknown): string | null {
299
+ const text =
300
+ typeof output === "string" ? output : output === undefined ? "" : JSON.stringify(output);
301
+ return text.match(/"uri"\s*:\s*"(ui:\/\/[^"]+)"/)?.[1] ?? null;
302
+ }
303
+
304
+ function summarise(input: unknown): string {
305
+ if (input === undefined || input === null) {
306
+ return "";
307
+ }
308
+ if (typeof input === "string") {
309
+ return input;
310
+ }
311
+ const record = input as Record<string, unknown>;
312
+ for (const key of ["command", "cmd", "query", "path", "url", "name"]) {
313
+ const value = record[key];
314
+ if (typeof value === "string" && value.trim()) {
315
+ return value;
316
+ }
317
+ }
318
+ const json = JSON.stringify(input);
319
+ return json.length > 120 ? `${json.slice(0, 117)}…` : json;
320
+ }
321
+
322
+ export interface AgentToolCardProps {
323
+ entry: AgentToolEntry;
324
+ }
325
+
326
+ /**
327
+ * The default card. It shows the tool's name, its input and its output — the
328
+ * input being the part that was missing for the whole of the AG-UI path,
329
+ * because the bridge had no `TOOL_CALL_ARGS` case.
330
+ */
331
+ function AgentToolCard({ entry }: AgentToolCardProps) {
332
+ const [open, setOpen] = React.useState(false);
333
+ const summary = summarise(entry.input);
334
+ return (
335
+ <div
336
+ data-slot="agent-tool-card"
337
+ data-tool={entry.name}
338
+ data-status={entry.status}
339
+ className={cn(
340
+ "overflow-hidden rounded-[var(--ds-radius-sm)] border border-[var(--ds-border-subtle)]",
341
+ "bg-[var(--ds-muted)]",
342
+ )}
343
+ >
344
+ <button
345
+ type="button"
346
+ aria-expanded={open}
347
+ onClick={() => setOpen((v) => !v)}
348
+ className={cn(
349
+ "flex w-full items-center gap-2.5 px-3 py-2 text-left",
350
+ "transition-colors duration-[var(--ds-duration-fast)] hover:bg-[var(--ds-hover)]",
351
+ )}
352
+ >
353
+ <span className="inline-flex size-3.5 shrink-0 items-center justify-center">
354
+ {entry.status === "running" ? (
355
+ <Spinner size={14} />
356
+ ) : (
357
+ <span
358
+ aria-hidden
359
+ className={cn(
360
+ "size-2 rounded-[var(--ds-radius-full)]",
361
+ entry.status === "error" ? "bg-[var(--ds-destructive)]" : "bg-[var(--ds-success)]",
362
+ )}
363
+ />
364
+ )}
365
+ </span>
366
+ <span className="font-mono text-[length:var(--ds-text-caption)] text-[color:var(--ds-primary)]">
367
+ {entry.name}
368
+ </span>
369
+ {summary ? (
370
+ <span
371
+ data-slot="agent-tool-card-input"
372
+ className="min-w-0 truncate text-[length:var(--ds-text-caption)] text-[color:var(--ds-muted-foreground)]"
373
+ >
374
+ {summary}
375
+ </span>
376
+ ) : null}
377
+ <span className="ml-auto shrink-0 text-[color:var(--ds-text-tertiary)]">
378
+ {open ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}
379
+ </span>
380
+ </button>
381
+ {open ? (
382
+ <div className="border-t border-[var(--ds-border-subtle)] bg-[var(--ds-background)] px-3 py-2">
383
+ {entry.input !== undefined ? (
384
+ <pre
385
+ data-slot="agent-tool-card-args"
386
+ className="max-h-40 overflow-auto font-mono text-[length:var(--ds-text-caption-sm)] whitespace-pre-wrap text-[color:var(--ds-muted-foreground)]"
387
+ >
388
+ {typeof entry.input === "string" ? entry.input : JSON.stringify(entry.input, null, 2)}
389
+ </pre>
390
+ ) : null}
391
+ {entry.output !== undefined && entry.output !== null ? (
392
+ <pre className="mt-2 max-h-40 overflow-auto font-mono text-[length:var(--ds-text-caption-sm)] whitespace-pre-wrap text-[color:var(--ds-muted-foreground)]">
393
+ {typeof entry.output === "string"
394
+ ? entry.output
395
+ : JSON.stringify(entry.output, null, 2)}
396
+ </pre>
397
+ ) : null}
398
+ </div>
399
+ ) : null}
400
+ </div>
401
+ );
402
+ }
403
+
404
+ export interface AgentApprovalCardProps {
405
+ request: AgentApprovalRequest;
406
+ onResolve: (id: string, decision: "allow-once" | "allow-always" | "deny") => void;
407
+ }
408
+
409
+ /**
410
+ * `exec` as a render-and-wait card: the run is paused on this decision.
411
+ *
412
+ * The three answers are the three cortenacore accepts. "Always allow" is not a
413
+ * nicety — without it the same command is asked about on every turn, and a user
414
+ * who has to answer the same question repeatedly stops reading the question.
415
+ */
416
+ function AgentApprovalCard({ request, onResolve }: AgentApprovalCardProps) {
417
+ const command =
418
+ typeof request.args.command === "string" ? request.args.command : request.toolName;
419
+ return (
420
+ <div
421
+ data-slot="agent-approval-card"
422
+ role="group"
423
+ aria-label="Command approval required"
424
+ className={cn(
425
+ "flex flex-col gap-3 rounded-[var(--ds-radius-md)] border border-[var(--ds-border)]",
426
+ "bg-[var(--ds-card)] p-3",
427
+ )}
428
+ >
429
+ <div className="flex items-center gap-2">
430
+ <ShieldCheck className="size-4 text-[color:var(--ds-primary)]" aria-hidden />
431
+ <span className="text-[length:var(--ds-text-body-sm)] font-medium text-[color:var(--ds-foreground)]">
432
+ Approval required
433
+ </span>
434
+ </div>
435
+ <pre className="max-h-32 overflow-auto rounded-[var(--ds-radius-sm)] bg-[var(--ds-muted)] p-2 font-mono text-[length:var(--ds-text-caption)] whitespace-pre-wrap text-[color:var(--ds-foreground)]">
436
+ {command}
437
+ </pre>
438
+ {/* A decision the server refused. The card came back rather than
439
+ vanishing, so the answer can be given again. */}
440
+ {request.error ? (
441
+ <p
442
+ data-slot="agent-approval-error"
443
+ role="alert"
444
+ className="text-[length:var(--ds-text-caption)] text-[color:var(--ds-destructive)]"
445
+ >
446
+ {request.error}
447
+ </p>
448
+ ) : null}
449
+ <div className="flex flex-wrap items-center gap-2">
450
+ <Button size="sm" onClick={() => onResolve(request.id, "allow-once")}>
451
+ <ShieldCheck aria-hidden />
452
+ Approve
453
+ </Button>
454
+ <Button size="sm" variant="outline" onClick={() => onResolve(request.id, "allow-always")}>
455
+ Always allow
456
+ </Button>
457
+ <Button size="sm" variant="destructive" onClick={() => onResolve(request.id, "deny")}>
458
+ <ShieldX aria-hidden />
459
+ Deny
460
+ </Button>
461
+ </div>
462
+ </div>
463
+ );
464
+ }
465
+
466
+ /* ── the surface ─────────────────────────────────────────────────────────── */
467
+
468
+ export interface AgentToolRenderContext {
469
+ entry: AgentToolEntry;
470
+ /** The `ui://` resource this result carries, when it carries one. */
471
+ mcpAppUri: string | null;
472
+ }
473
+
474
+ export interface AgentChatProps extends Omit<React.ComponentProps<"div">, "children" | "onError"> {
475
+ /** The transport. `createAguiAgentChatClient` is the AG-UI implementation. */
476
+ client: AgentChatClient;
477
+ /** The extension name, shown on each assistant turn. */
478
+ agentName: string;
479
+ /**
480
+ * Names the `sessionStorage` slot this window's session key lives in. Scope
481
+ * it to the extension id; two chats with different scopes never share a key.
482
+ */
483
+ storageScope: string;
484
+ /** Do not read or write `sessionStorage`; for a guide or a test. */
485
+ ephemeral?: boolean;
486
+ thinking?: "low" | "medium" | "high";
487
+ /** Rendered between the tool strip and the composer — an attachment picker. */
488
+ attachmentsSlot?: React.ReactNode;
489
+ /**
490
+ * Host wiring for a tool call. Return a node to replace the default card —
491
+ * this is the seam an MCP App frame mounts through, since the sandboxed
492
+ * iframe, its CSP and the `tools/invoke` proxy are the host's to own.
493
+ */
494
+ renderToolCall?: (context: AgentToolRenderContext) => React.ReactNode | undefined;
495
+ /** Header content, e.g. the pop-up's own window controls. */
496
+ headerSlot?: React.ReactNode;
497
+ }
498
+
499
+ function AgentChat({
500
+ client,
501
+ agentName,
502
+ storageScope,
503
+ ephemeral,
504
+ thinking,
505
+ attachmentsSlot,
506
+ renderToolCall,
507
+ headerSlot,
508
+ className,
509
+ ...props
510
+ }: AgentChatProps) {
511
+ const chat = useAgentChat({
512
+ client,
513
+ storageScope,
514
+ ...(ephemeral === undefined ? {} : { ephemeral }),
515
+ ...(thinking === undefined ? {} : { thinking }),
516
+ });
517
+ const [drawerOpen, setDrawerOpen] = React.useState(false);
518
+ const [value, setValue] = React.useState("");
519
+ const scrollRef = React.useRef<HTMLDivElement>(null);
520
+ const contentRef = React.useRef<HTMLDivElement>(null);
521
+ const prevHeightRef = React.useRef(0);
522
+
523
+ /**
524
+ * Re-pin to the bottom whenever the content grows or the viewport shrinks.
525
+ * A message keeps growing after it mounts — markdown settles, the tool strip
526
+ * appears between the list and the composer — and every one of those leaves
527
+ * the newest content under the composer until the reader scrolls by hand.
528
+ *
529
+ * Jumping rather than smooth-scrolling: this fires many times a second during
530
+ * streaming, and queued smooth animations fight each other and lose.
531
+ */
532
+ React.useEffect(() => {
533
+ const scrollEl = scrollRef.current;
534
+ const contentEl = contentRef.current;
535
+ if (!scrollEl || !contentEl || typeof ResizeObserver === "undefined") {
536
+ return;
537
+ }
538
+ const observer = new ResizeObserver(() => {
539
+ const { scrollTop, scrollHeight, clientHeight } = scrollEl;
540
+ const stick = shouldStickToBottom({
541
+ prevScrollHeight: prevHeightRef.current,
542
+ scrollTop,
543
+ clientHeight,
544
+ });
545
+ prevHeightRef.current = scrollHeight;
546
+ if (stick) {
547
+ scrollEl.scrollTop = scrollEl.scrollHeight;
548
+ }
549
+ });
550
+ observer.observe(contentEl);
551
+ observer.observe(scrollEl);
552
+ return () => observer.disconnect();
553
+ }, []);
554
+
555
+ const submit = React.useCallback(() => {
556
+ const trimmed = value.trim();
557
+ // Enter reaches here while a run is live, where the button is a Stop
558
+ // control and cannot be pressed. One run at a time, by both routes.
559
+ if (!trimmed || chat.streaming) {
560
+ return;
561
+ }
562
+ chat.send(trimmed);
563
+ setValue("");
564
+ }, [chat, value]);
565
+
566
+ const onKeyDown = React.useCallback(
567
+ (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
568
+ if (event.key === "Escape" && chat.streaming) {
569
+ // Escape stops the run. It does not close the pop-up while a run is in
570
+ // flight: the first Escape is nearly always "stop", not "go away".
571
+ event.preventDefault();
572
+ event.stopPropagation();
573
+ chat.abort();
574
+ return;
575
+ }
576
+ if (event.key === "Enter" && !event.shiftKey) {
577
+ event.preventDefault();
578
+ submit();
579
+ }
580
+ },
581
+ [chat, submit],
582
+ );
583
+
584
+ const toolEntries = chat.toolOrder
585
+ .map((id) => chat.tools[id])
586
+ .filter((entry): entry is AgentToolEntry => entry !== undefined);
587
+ // The strip outlives the run rather than vanishing with it. The steps of a
588
+ // finished turn are the record of what the agent did on the user's behalf,
589
+ // and an MCP App drawn by one of them is a surface the user is meant to work
590
+ // in — one that disappeared the instant the agent stopped talking would be no
591
+ // use to anybody. The next run clears it.
592
+ const showTools = toolEntries.length > 0 || chat.approvals.length > 0;
593
+ const visible = chat.messages.filter((message) => !isHiddenMessage(message));
594
+
595
+ return (
596
+ <div
597
+ data-slot="agent-chat"
598
+ className={cn("flex h-full min-h-0 w-full flex-col bg-[var(--ds-background)]", className)}
599
+ {...props}
600
+ >
601
+ <div
602
+ data-slot="agent-chat-header"
603
+ className={cn(
604
+ "flex shrink-0 items-center gap-2 border-b border-[var(--ds-border-subtle)] px-3 py-2",
605
+ )}
606
+ >
607
+ <Button
608
+ size="sm"
609
+ variant="ghost"
610
+ data-slot="agent-chat-sessions-trigger"
611
+ aria-expanded={drawerOpen}
612
+ onClick={() => {
613
+ setDrawerOpen((open) => !open);
614
+ chat.refreshSessions();
615
+ }}
616
+ >
617
+ {chat.sessions.length === 1 ? "1 session" : `${chat.sessions.length} sessions`}
618
+ </Button>
619
+ <Button
620
+ size="sm"
621
+ variant="ghost"
622
+ data-slot="agent-chat-new-session"
623
+ aria-label="New session"
624
+ onClick={() => {
625
+ chat.newSession();
626
+ setDrawerOpen(false);
627
+ }}
628
+ >
629
+ <MessageSquarePlus aria-hidden />
630
+ New
631
+ </Button>
632
+ <div className="ml-auto flex items-center gap-1">{headerSlot}</div>
633
+ </div>
634
+
635
+ {drawerOpen ? (
636
+ <AgentSessionDrawer
637
+ sessions={chat.sessions}
638
+ current={chat.sessionKey}
639
+ loading={chat.loadingSessions}
640
+ onResume={(key) => {
641
+ chat.resumeSession(key);
642
+ setDrawerOpen(false);
643
+ }}
644
+ />
645
+ ) : null}
646
+
647
+ <div
648
+ ref={scrollRef}
649
+ data-slot="agent-chat-scroll"
650
+ className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto"
651
+ >
652
+ <div
653
+ ref={contentRef}
654
+ role="log"
655
+ aria-live="polite"
656
+ aria-label={`${agentName} chat`}
657
+ className="flex min-w-0 flex-col gap-5 px-4 py-4"
658
+ >
659
+ {chat.error ? (
660
+ <ErrorBanner message={chat.error} />
661
+ ) : null}
662
+
663
+ {chat.hasMoreHistory ? (
664
+ <div className="flex justify-center">
665
+ <Button
666
+ size="sm"
667
+ variant="ghost"
668
+ data-slot="agent-chat-load-older"
669
+ disabled={chat.loadingHistory}
670
+ onClick={chat.loadOlder}
671
+ >
672
+ {chat.loadingHistory ? "Loading…" : "Load older messages"}
673
+ </Button>
674
+ </div>
675
+ ) : null}
676
+
677
+ {visible.length === 0 && !chat.streaming ? (
678
+ <p
679
+ data-slot="agent-chat-empty"
680
+ className="text-[length:var(--ds-text-caption-lg)] text-[color:var(--ds-muted-foreground)]"
681
+ >
682
+ Ask {agentName} anything about this screen.
683
+ </p>
684
+ ) : null}
685
+
686
+ {visible.map((message) => (
687
+ <AgentMessageBubble
688
+ key={message.id}
689
+ message={message}
690
+ agentName={agentName}
691
+ streaming={chat.streaming}
692
+ onAction={chat.sendAction}
693
+ />
694
+ ))}
695
+
696
+ {chat.streaming ? (
697
+ <AgentStreamingBubble
698
+ agentName={agentName}
699
+ text={chat.streamText}
700
+ thinkingText={chat.streamThinkingText}
701
+ a2ui={chat.streamA2ui}
702
+ />
703
+ ) : null}
704
+ </div>
705
+ </div>
706
+
707
+ {showTools ? (
708
+ <div
709
+ data-slot="agent-chat-tools"
710
+ className="flex shrink-0 flex-col gap-1.5 border-t border-[var(--ds-border-subtle)] px-3 py-2"
711
+ >
712
+ {toolEntries.length > 0 ? (
713
+ <Badge variant="neutral" className="w-fit">
714
+ {toolEntries.length === 1 ? "1 step" : `${toolEntries.length} steps`}
715
+ </Badge>
716
+ ) : null}
717
+ {toolEntries.map((entry) => {
718
+ const custom = renderToolCall?.({ entry, mcpAppUri: readMcpAppUri(entry.output) });
719
+ return (
720
+ <React.Fragment key={entry.id}>
721
+ {custom ?? <AgentToolCard entry={entry} />}
722
+ </React.Fragment>
723
+ );
724
+ })}
725
+ {chat.approvals.map((request) => (
726
+ <AgentApprovalCard key={request.id} request={request} onResolve={chat.resolveApproval} />
727
+ ))}
728
+ </div>
729
+ ) : null}
730
+
731
+ {attachmentsSlot ? (
732
+ <div data-slot="agent-chat-attachments" className="shrink-0 px-3">
733
+ {attachmentsSlot}
734
+ </div>
735
+ ) : null}
736
+
737
+ <div
738
+ data-slot="agent-chat-composer"
739
+ className="flex shrink-0 items-end gap-2 border-t border-[var(--ds-border-subtle)] p-3"
740
+ >
741
+ <Textarea
742
+ data-slot="agent-chat-input"
743
+ aria-label={`Message ${agentName}`}
744
+ placeholder={`Message ${agentName}…`}
745
+ rows={1}
746
+ className="max-h-40 min-h-9 resize-none"
747
+ value={value}
748
+ onChange={(event) => setValue(event.target.value)}
749
+ onKeyDown={onKeyDown}
750
+ />
751
+ {chat.streaming ? (
752
+ <Button
753
+ size="icon"
754
+ variant="outline"
755
+ data-slot="agent-chat-stop"
756
+ aria-label="Stop the run"
757
+ onClick={chat.abort}
758
+ >
759
+ <Square aria-hidden />
760
+ </Button>
761
+ ) : (
762
+ <Button
763
+ size="icon"
764
+ data-slot="agent-chat-send"
765
+ aria-label="Send"
766
+ disabled={!value.trim()}
767
+ onClick={submit}
768
+ >
769
+ <Send aria-hidden />
770
+ </Button>
771
+ )}
772
+ </div>
773
+ </div>
774
+ );
775
+ }
776
+
777
+ /* ── the session drawer ──────────────────────────────────────────────────── */
778
+
779
+ export interface AgentSessionDrawerProps {
780
+ sessions: readonly AgentSession[];
781
+ current: string | null;
782
+ loading?: boolean;
783
+ onResume: (key: string) => void;
784
+ }
785
+
786
+ /**
787
+ * Every session of this agent, resumable from any window.
788
+ *
789
+ * The list is not this window's history: a session started in another window is
790
+ * here and can be resumed, which is the difference between "sessions are per
791
+ * window" (which key a window starts on) and "sessions are private to a window"
792
+ * (which they are not).
793
+ */
794
+ function AgentSessionDrawer({ sessions, current, loading, onResume }: AgentSessionDrawerProps) {
795
+ return (
796
+ <div
797
+ data-slot="agent-chat-sessions"
798
+ className={cn(
799
+ "max-h-56 shrink-0 overflow-y-auto border-b border-[var(--ds-border-subtle)]",
800
+ "bg-[var(--ds-card)] px-2 py-1.5",
801
+ )}
802
+ >
803
+ {loading && sessions.length === 0 ? (
804
+ <p className="px-2 py-1 text-[length:var(--ds-text-caption)] text-[color:var(--ds-muted-foreground)]">
805
+ Loading sessions…
806
+ </p>
807
+ ) : null}
808
+ {!loading && sessions.length === 0 ? (
809
+ <p className="px-2 py-1 text-[length:var(--ds-text-caption)] text-[color:var(--ds-muted-foreground)]">
810
+ No earlier sessions.
811
+ </p>
812
+ ) : null}
813
+ {sessions.map((session) => (
814
+ <button
815
+ key={session.key}
816
+ type="button"
817
+ data-slot="agent-chat-session"
818
+ data-current={session.key === current ? "" : undefined}
819
+ onClick={() => onResume(session.key)}
820
+ className={cn(
821
+ "flex w-full items-center gap-2 rounded-[var(--ds-radius-sm)] px-2 py-1.5 text-left",
822
+ "text-[length:var(--ds-text-caption-lg)] text-[color:var(--ds-foreground)]",
823
+ "transition-colors duration-[var(--ds-duration-fast)] hover:bg-[var(--ds-hover)]",
824
+ session.key === current && "bg-[var(--ds-primary-soft)]",
825
+ )}
826
+ >
827
+ <span className="min-w-0 truncate">{sessionTitle(session)}</span>
828
+ </button>
829
+ ))}
830
+ </div>
831
+ );
832
+ }
833
+
834
+ export {
835
+ AgentA2UIBlocks,
836
+ AgentApprovalCard,
837
+ AgentChat,
838
+ AgentMessageBubble,
839
+ AgentSessionDrawer,
840
+ AgentStreamingBubble,
841
+ AgentThinking,
842
+ AgentToolCard,
843
+ };