-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathChatbotEnhanced.tsx
More file actions
1813 lines (1758 loc) · 70.4 KB
/
Copy pathChatbotEnhanced.tsx
File metadata and controls
1813 lines (1758 loc) · 70.4 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
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* ChatbotEnhanced — composed on top of vendored Vercel AI Elements
* (src/elements/, MIT). Public props remain backwards compatible with the
* previous custom implementation; internally we now get:
* - multi-line auto-growing prompt input (PromptInput)
* - smart reverse-stick scroll (Conversation + useStickToBottom)
* - message action toolbar surface (Message.actions slot)
* - tool-call visualisation (Tool* family)
* - reasoning / chain-of-thought collapsible (Reasoning*)
* - inline citations / sources panel (Sources*)
* - suggestion chips on empty state (Suggestion / Suggestions)
* - streaming markdown via streamdown (used by Message internals)
*/
import * as React from 'react';
import { cn } from '@object-ui/components';
import { AlertCircle, ArrowRight, Copy, Check, RefreshCw, CornerDownLeft, Bot, Eye, GitCompareArrows, Rocket, Clock3, CheckCircle2, XCircle, Loader2 } from 'lucide-react';
import type { ChatStatus } from 'ai';
import {
humanizeToolName,
summarizeChatError,
unwrapToolResult,
} from './tool-display';
import {
Conversation,
ConversationContent,
ConversationEmptyState,
ConversationScrollButton,
} from './elements/conversation';
import {
Message,
MessageActions,
MessageAction,
MessageContent,
MessageResponse,
type MessageProps,
} from './elements/message';
import {
PromptInput,
PromptInputBody,
PromptInputTextarea,
PromptInputFooter,
PromptInputTools,
PromptInputSubmit,
PromptInputAttachments,
PromptInputAttachment,
PromptInputActionMenu,
PromptInputActionMenuTrigger,
PromptInputActionMenuContent,
PromptInputActionAddAttachments,
type PromptInputMessage,
} from './elements/prompt-input';
import { Suggestion, Suggestions } from './elements/suggestion';
import {
Tool,
ToolHeader,
ToolContent,
ToolInput,
ToolOutput,
} from './elements/tool';
import {
Reasoning,
ReasoningTrigger,
ReasoningContent,
} from './elements/reasoning';
import {
Sources,
SourcesTrigger,
SourcesContent,
Source,
} from './elements/sources';
export interface ChatMessage {
id: string;
role: 'user' | 'assistant' | 'system';
content: string;
timestamp?: string;
avatar?: string;
avatarFallback?: string;
/** Streaming flag — surfaces a shimmer cursor on the assistant bubble. */
streaming?: boolean;
/**
* Tool invocations attached to this message. Mirrors the AI SDK's
* `ToolUIPart` shape (see `vercel/ai` v3) so we can render them with the
* vendored `<Tool>` element without any extra mapping.
*/
toolInvocations?: ChatToolInvocation[];
/** Chain-of-thought / reasoning text emitted alongside the answer. */
reasoning?: string;
/** Optional citation / RAG sources for this assistant message. */
sources?: ChatSource[];
/** Optional backend trace id (e.g. `ai_traces.id`) for debugging. */
traceId?: string;
/**
* Live build progress from a long-running tool (apply_blueprint), lifted from
* the stream's reconciled `data-build-progress` part. When present, the chat
* renders a growing "build tree" so the user watches the app take shape
* instead of staring at a thinking spinner.
*/
buildProgress?: ChatBuildProgress;
}
/** A reconciled snapshot of an in-flight app build (apply_blueprint). */
export interface ChatBuildProgress {
/** Coarse phase: drafting structure, generating sample data, or finished. */
phase: 'structure' | 'data' | 'done';
/** Human label for the app being built (for the panel header). */
appLabel?: string;
/** Artifacts drafted so far, cumulative. */
items: Array<{ type: string; name: string }>;
/** Count of artifacts done and the rough total (for the progress bar). */
done: number;
total: number;
}
export interface ChatToolInvocation {
toolCallId: string;
toolName: string;
args?: unknown;
result?: unknown;
errorText?: string;
/**
* AI SDK v6 lifecycle states for a tool part. Defaults to
* `output-available` when only `result` is present and `input-available`
* when only `args` is present.
*/
state?:
| 'input-streaming'
| 'input-available'
| 'approval-requested'
| 'approval-responded'
| 'output-available'
| 'output-error'
| 'output-denied';
/**
* ObjectStack HITL extension. When the framework's `action-tools.ts`
* proposes a destructive action that requires human approval, the tool
* result carries `{ status: 'pending_approval', pendingActionId: 'pa_…' }`.
* `mapMessages.ts` lifts that id here so chat UIs can call the
* `POST /api/v1/ai/pending-actions/:id/{approve,reject}` REST endpoints
* without parsing the tool result JSON themselves.
*/
pendingActionId?: string;
/**
* ObjectStack ADR-0033 extension. When a metadata-authoring tool stages a
* change as a DRAFT, its result carries `{ status: 'drafted', type, name, … }`
* (or a `drafted: [{type,name}]` batch from `apply_blueprint`). `mapMessages.ts`
* lifts the reviewable targets here so chat UIs can render a "Review N
* change(s)" affordance that opens the designer's review/diff. Nothing is
* live until the human publishes — this is the review entry point.
*/
draftReview?: {
items: Array<{ type: string; name: string }>;
summary?: string;
packageId?: string;
/**
* Backend lifecycle intent (from the tool result). `true` for whole-app
* builds (apply_blueprint) — eligible for the auto-publish "magic moment".
* Omitted for incremental edits, which stay drafts for explicit review.
*/
autoPublishable?: boolean;
/** Count of artifacts that failed in a partial build, surfaced not hidden. */
failedCount?: number;
/**
* ADR-0045: the build was MATERIALIZED in-turn — real tables and seed
* rows exist; the app is live but `hidden` (unlisted). Preview should
* open the REAL app URL, not the draft overlay.
*/
materialized?: boolean;
};
}
export interface ChatSource {
id?: string;
title?: string;
url: string;
}
/**
* Localizable UI strings for the chat surface. Every field is optional and
* falls back to an English default, keeping existing callers source-compatible.
*/
export interface ChatbotLabels {
/** Empty-state heading shown before the first message. */
emptyTitle?: string;
/** Empty-state supporting line. */
emptyDescription?: string;
/** "Clear conversation" action label. */
clear?: string;
/** Trailing hint next to the send button (e.g. "to send"). */
sendHint?: string;
/** Compact agent activity heading shown in summary mode. */
agentActivity?: string;
/** Status label for completed tool work. */
toolCompleted?: string;
/** Status label for running tool work. */
toolRunning?: string;
/** Status label for tool work waiting for approval. */
toolAwaitingApproval?: string;
/** Status label for failed tool work. */
toolFailed?: string;
/** Helper text explaining that raw internals are hidden. */
toolDetailsHidden?: string;
/** Message action label for copying assistant text. */
copy?: string;
/** Message action label shown after a successful copy. */
copied?: string;
/** Message action label for regenerating the last assistant response. */
regenerate?: string;
/** Accessible label for the model picker. */
model?: string;
/** Accessible label for the submit button. */
submit?: string;
/** Accessible label for the attachment file picker. */
uploadFiles?: string;
/** Accessible label for the stop-streaming button. */
stopResponse?: string;
/** Trace link label in debug mode. */
trace?: string;
/** Trace link tooltip in debug mode. */
viewTrace?: string;
}
export type ChatbotProcessVisibility = 'hidden' | 'summary' | 'debug';
export type ChatbotSurface = 'card' | 'plain';
export interface ChatbotEnhancedProps extends React.HTMLAttributes<HTMLDivElement> {
messages?: ChatMessage[];
placeholder?: string;
/**
* Send handler. Signature kept backwards compatible — `files` is the list
* of attachments selected via the prompt-input action menu.
*/
onSendMessage?: (message: string, files?: File[]) => void;
onClear?: () => void;
/** Stop the current streaming response */
onStop?: () => void;
/** Reload / retry the last assistant message */
onReload?: () => void;
disabled?: boolean;
/** Whether the assistant is currently generating a response */
isLoading?: boolean;
/** Current streaming/API error */
error?: Error;
showTimestamp?: boolean;
/**
* Render avatars beside each message (assistant gets a bot glyph, the user
* gets their initial / image). Defaults to false to preserve the previous
* minimal layout for existing callers.
*/
showAvatars?: boolean;
userAvatarUrl?: string;
userAvatarFallback?: string;
assistantAvatarUrl?: string;
assistantAvatarFallback?: string;
/**
* Hide the internal "clear conversation" strip. Hosts that surface a clear
* / new-chat control in their own chrome (e.g. a floating panel header) set
* this to avoid a redundant second header row.
*/
hideClearBar?: boolean;
maxHeight?: string;
/** Kept for back-compat — markdown is now always rendered by streamdown. */
enableMarkdown?: boolean;
/** Enable the attachment action menu. */
enableFileUpload?: boolean;
/** Comma-separated list (or accept string) forwarded to the file picker. */
acceptedFileTypes?: string;
/** Max file size in bytes (default 10 MB). */
maxFileSize?: number;
/**
* Optional suggestion chips rendered on the empty conversation state.
* Clicking a chip submits the message immediately.
*/
suggestions?: string[];
/**
* Optional UI string overrides for localization. Each field falls back
* to its English default, so existing callers keep working unchanged.
*/
labels?: ChatbotLabels;
/**
* Available LLM models for the picker (sourced from
* `GET /api/v1/ai/models` exposed by `@objectstack/service-ai`).
*/
models?: ChatbotModelOption[];
/** Currently selected model id (controlled). */
selectedModelId?: string;
/** Fired when the user picks a different model. */
onModelChange?: (modelId: string) => void;
/**
* Optional banner rendered between the message-count strip and the
* conversation. Used by shell-level UIs (e.g. Studio's assistant status
* row) without forcing them to fork the whole component.
*/
headerSlot?: React.ReactNode;
/**
* Optional overlay rendered absolute-positioned above the prompt input.
* Intended for slash-command palettes / inline suggestion popups.
*/
promptOverlaySlot?: React.ReactNode;
/**
* Fired on every keystroke in the prompt textarea (forwarded from the
* AI Elements `PromptInputTextarea`). Lets callers drive a slash-command
* palette without owning the textarea state.
*/
onInputChange?: (value: string) => void;
/**
* When provided, tool parts in `approval-requested` state render Approve /
* Deny buttons inside their body. The callback receives the tool's
* `toolCallId` (use it to look up the AI SDK approval id if different).
*/
onToolApprove?: (toolCallId: string, approved: boolean, reason?: string) => void;
/** Label for the approve button (default "Approve"). */
toolApproveLabel?: string;
/** Label for the deny button (default "Deny"). */
toolDenyLabel?: string;
/** Reason text sent with a denial response (default "User denied the operation"). */
toolDenyReason?: string;
/**
* Client-side overlay for HITL approval outcomes, keyed by `toolCallId`.
* Driven by `useHitlInChat` (or any caller-owned map). When an entry is
* present for a tool in `approval-requested` state, the inline buttons are
* hidden and the configured message renders in their place — giving the
* operator immediate feedback while the server processes the decision.
*/
toolDecisions?: Record<string, ToolDecisionState>;
/**
* When provided, tool parts whose result drafted metadata (ADR-0033) render a
* "Review N change(s)" button inside their body. The callback receives the
* reviewable `{ type, name }` targets; the host typically navigates to the
* designer's review/diff. See `ChatToolInvocation.draftReview`.
*/
onReviewDraft?: (items: Array<{ type: string; name: string }>) => void;
/** Label for the review-draft button (default "Review {n} change(s)"). */
toolReviewLabel?: (count: number) => string;
/**
* When provided AND the drafted tool result reported its owning `packageId`,
* tool parts render a one-click "Publish" button so the human can promote the
* staged drafts to live without leaving the conversation (the ADR-0033 gate
* stays — the human still clicks). The host wires this to
* `POST /api/v1/packages/:packageId/publish-drafts`.
*
* Return value (all forms accepted, `false`/`{ok:false}` = failure):
* - `boolean | void` — legacy success flag;
* - `{ ok: boolean; health?: PublishHealth }` — ADR-0038 L3: the publish
* response's `seedApplied` + runtime `probes`, rendered as a build-health
* line under the Published badge so "Published" and "actually works" are
* two separately-verified statements.
*/
onPublishDrafts?: (
packageId: string,
) => void | boolean | PublishOutcome | Promise<void | boolean | PublishOutcome>;
/**
* When provided, a finished build tree (`buildProgress.phase === 'done'`) that
* created an `app` renders an "Open app" action so the user can jump straight
* into what was just built. The host wires this to its router (e.g.
* `navigate('/apps/<name>')`).
*/
onOpenBuiltApp?: (appName: string) => void;
/** Label for the open-built-app action (default "Open app"). */
openBuiltAppLabel?: string;
/**
* ADR-0037 Live Canvas: preview the drafted app *before* it is published.
* Rendered next to the build tree's Open-app action and on draft chips
* whose items include an `app`. The host wires this to its router with the
* preview flag (e.g. `navigate('/apps/<name>?preview=draft')`).
* ADR-0045: when the build reports `materialized`, `opts.materialized` is
* true and the host should open the REAL app URL (no preview flag) — the
* app is live-but-unlisted, with actual tables and seed data.
*/
onPreviewDraftApp?: (appName: string, opts?: { materialized?: boolean }) => void;
/** Label for the preview-draft action (default "Preview"). */
previewDraftLabel?: string;
/**
* ADR-0037 Live Canvas: notifies the host whenever AI-authored draft
* artifacts land in the conversation (build-progress items + drafted
* envelopes), with the cumulative deduped set. Hosts use it to open and
* refresh the live draft-preview pane while the agent builds.
*/
onDraftArtifacts?: (artifacts: Array<{ type: string; name: string }>) => void;
/**
* ADR-0045: fires once per build whose tool result reports `materialized`
* with an `app` in the draft set — the app is live (tables + seed data)
* but unlisted. Hosts switch the canvas to the real app URL.
*/
onBuildMaterialized?: (appName: string) => void;
/** Label for the publish-drafts button (default "Publish"). */
publishDraftsLabel?: string;
/** Label for the published-state badge that replaces the button (default "Published"). */
publishedLabel?: string;
/**
* Auto-fire `onPublishDrafts` the moment a turn finishes drafting an app —
* the self-use "magic moment" where the user refreshes and the app is already
* live WITH data, instead of clicking Publish. Server-gated by the plan
* (`features.autoPublishAiBuilds`, env-revertible via
* `OS_AI_AUTOPUBLISH_DISABLED`); the host passes the resolved flag.
*
* Only NEW drafts from the current session fire — drafts already present when
* the chat mounts (e.g. reopening a conversation) are left for the manual
* Publish button, so reopening history never silently publishes.
*
* @default false
*/
autoPublishDrafts?: boolean;
/**
* Controls how agent internals are exposed. `summary` keeps end-user chat
* readable by grouping repeated tool calls and hiding raw args/results.
* Use `debug` for developer/admin trace views.
*
* @default 'summary'
*/
processVisibility?: ChatbotProcessVisibility;
/**
* Visual chrome for the chat surface. `card` keeps the embeddable bordered
* panel; `plain` removes panel chrome for full-page chat workspaces.
*
* @default 'card'
*/
surface?: ChatbotSurface;
}
/**
* ADR-0038 L3 — what a publish actually did at runtime. Hosts extract this
* from the publish-drafts response (`seedApplied` + `probes`) so the chat can
* render a build-health line: "Published" and "actually works" are two
* separately-verified statements, and the second one must be visible too.
*/
export interface PublishHealth {
/** Rows materialized by published seeds (`seedApplied` inserted+updated). */
seededRows?: number;
/** Seed-load failure detail when sample data did NOT land. */
seedError?: string;
/** How many runtime probes ran per plane (`probes.checked`). */
checked?: { seeds: number; views: number; widgets: number };
/** Runtime findings (`probes.issues`), already human-readable. */
issues?: Array<{ severity: 'error' | 'warning'; code: string; message: string }>;
}
/** Structured result of `onPublishDrafts` — richer alternative to a bare boolean. */
export interface PublishOutcome {
ok: boolean;
health?: PublishHealth;
}
/**
* Extract {@link PublishHealth} from a publish-drafts response body (tolerant
* of the dispatcher's `{ success, data }` envelope). Shared by the hosts that
* wire `onPublishDrafts` so they all read `seedApplied` + `probes` the same
* way; returns undefined when the server reported neither (older runtimes).
*/
export function publishHealthFromResponse(payload: unknown): PublishHealth | undefined {
const root = (payload ?? {}) as Record<string, unknown>;
const data = (root.data && typeof root.data === 'object' ? root.data : root) as Record<string, unknown>;
const seedApplied = data.seedApplied as
| { success?: boolean; inserted?: number; updated?: number; error?: string; errors?: unknown[] }
| undefined;
const probes = data.probes as
| {
checked?: { seeds?: number; views?: number; widgets?: number };
issues?: Array<{ severity?: string; code?: string; message?: string }>;
}
| undefined;
if (!seedApplied && !probes) return undefined;
const health: PublishHealth = {};
if (seedApplied) {
if (seedApplied.success === false) {
health.seedError =
seedApplied.error ??
(Array.isArray(seedApplied.errors) && seedApplied.errors.length
? String(seedApplied.errors[0])
: 'Sample data failed to load.');
} else {
health.seededRows = (seedApplied.inserted ?? 0) + (seedApplied.updated ?? 0);
}
}
if (probes) {
health.checked = {
seeds: probes.checked?.seeds ?? 0,
views: probes.checked?.views ?? 0,
widgets: probes.checked?.widgets ?? 0,
};
health.issues = (probes.issues ?? [])
.filter((i) => i && typeof i.message === 'string')
.map((i) => ({
severity: i.severity === 'error' ? 'error' : 'warning',
code: String(i.code ?? 'runtime_issue'),
message: String(i.message),
}));
}
return health;
}
export type ToolDecisionState =
| { state: 'pending'; message?: string }
| { state: 'success'; message?: string }
| { state: 'error'; message: string };
export interface ChatbotModelOption {
id: string;
label?: string;
provider?: string;
}
function formatMessageProps(role: ChatMessage['role']): MessageProps['from'] {
// The vendored Message only knows user/assistant — render system as assistant
// (FloatingChatbotProvider already renders system messages inline elsewhere).
return role === 'user' ? 'user' : 'assistant';
}
/**
* Heuristic: does a tool/output string look like JSON we should syntax-highlight
* (object / array literal) rather than render as markdown? Plain prose, code
* fences, and inline backticks should NOT be rendered as JSON.
*/
function looksLikeJson(text: string): boolean {
const t = text.trim();
if (t.length < 2) return false;
if (!(t.startsWith('{') || t.startsWith('['))) return false;
if (!(t.endsWith('}') || t.endsWith(']'))) return false;
try {
JSON.parse(t);
return true;
} catch {
return false;
}
}
type ToolSummaryState = 'running' | 'awaiting' | 'completed' | 'failed';
interface ToolSummaryGroup {
key: string;
title: string;
rawName: string;
count: number;
state: ToolSummaryState;
errorText?: string;
}
function getToolState(tool: ChatToolInvocation): ToolSummaryState {
const state =
tool.state ??
(tool.errorText
? 'output-error'
: tool.result !== undefined
? 'output-available'
: 'input-available');
if (state === 'output-error' || state === 'output-denied') {
return 'failed';
}
if (state === 'approval-requested' || state === 'approval-responded') {
return 'awaiting';
}
if (state === 'output-available') {
return 'completed';
}
return 'running';
}
function shouldRenderDetailedTool(tool: ChatToolInvocation): boolean {
const state = getToolState(tool);
return (
state === 'awaiting' ||
state === 'failed' ||
Boolean(tool.pendingActionId) ||
Boolean(tool.draftReview?.items.length)
);
}
function getToolStateRank(state: ToolSummaryState): number {
switch (state) {
case 'failed':
return 4;
case 'awaiting':
return 3;
case 'running':
return 2;
case 'completed':
return 1;
}
}
function summarizeTools(tools: ChatToolInvocation[]): ToolSummaryGroup[] {
const groups = new Map<string, ToolSummaryGroup>();
for (const tool of tools) {
const state = getToolState(tool);
const key = `${tool.toolName}:${state}`;
const existing = groups.get(key);
if (existing) {
existing.count += 1;
existing.errorText = existing.errorText ?? tool.errorText;
continue;
}
groups.set(key, {
key,
title: humanizeToolName(tool.toolName) || tool.toolName,
rawName: tool.toolName,
count: 1,
state,
errorText: tool.errorText,
});
}
return Array.from(groups.values()).sort((a, b) => {
const byRank = getToolStateRank(b.state) - getToolStateRank(a.state);
if (byRank !== 0) return byRank;
return a.title.localeCompare(b.title);
});
}
/**
* ADR-0038 L3 — the build-health line under a Published badge. Reads the
* publish's `seedApplied` + runtime-probe results and answers the question
* the badge alone can't: did the published app actually work when exercised?
* Renders nothing without health data (older hosts return a bare boolean).
*/
function PublishHealthLine({ health }: { health: PublishHealth | undefined }) {
if (!health) return null;
const issues = health.issues ?? [];
const errors = issues.filter((i) => i.severity === 'error');
const warnings = issues.filter((i) => i.severity !== 'error');
const checked = health.checked;
const probesRan = !!checked && checked.seeds + checked.views + checked.widgets > 0;
const okParts: string[] = [];
if (typeof health.seededRows === 'number' && health.seededRows > 0 && !health.seedError) {
okParts.push(`${health.seededRows} sample row${health.seededRows === 1 ? '' : 's'} live`);
}
if (probesRan && errors.length === 0) {
const planes: string[] = [];
if (checked!.views > 0) planes.push(`${checked!.views} view${checked!.views === 1 ? '' : 's'}`);
if (checked!.widgets > 0) planes.push(`${checked!.widgets} widget${checked!.widgets === 1 ? '' : 's'}`);
if (checked!.seeds > 0) planes.push(`${checked!.seeds} seed${checked!.seeds === 1 ? '' : 's'}`);
if (planes.length) okParts.push(`${planes.join(' · ')} verified`);
}
if (okParts.length === 0 && !health.seedError && issues.length === 0) return null;
return (
<div className="flex flex-col gap-1 border-t bg-muted/20 px-3 py-2" data-testid="publish-health">
{okParts.length > 0 ? (
<div className="flex items-center gap-1.5 text-xs text-emerald-700">
<CheckCircle2 className="size-3.5 shrink-0" />
<span>{okParts.join(' · ')}</span>
</div>
) : null}
{health.seedError ? (
<div className="flex items-start gap-1.5 text-xs text-red-600">
<XCircle className="mt-0.5 size-3.5 shrink-0" />
<span>{health.seedError}</span>
</div>
) : null}
{errors.map((i, idx) => (
<div key={`e${idx}`} className="flex items-start gap-1.5 text-xs text-red-600">
<XCircle className="mt-0.5 size-3.5 shrink-0" />
<span>{i.message}</span>
</div>
))}
{warnings.map((i, idx) => (
<div key={`w${idx}`} className="flex items-start gap-1.5 text-xs text-amber-600">
<AlertCircle className="mt-0.5 size-3.5 shrink-0" />
<span>{i.message}</span>
</div>
))}
</div>
);
}
const ChatbotEnhanced = React.forwardRef<HTMLDivElement, ChatbotEnhancedProps>(
(
{
className,
messages = [],
placeholder = 'Type your message...',
onSendMessage,
onClear,
onStop,
onReload,
disabled = false,
isLoading = false,
error,
showTimestamp = false,
showAvatars = false,
userAvatarUrl,
userAvatarFallback = 'You',
assistantAvatarUrl,
assistantAvatarFallback = 'AI',
hideClearBar = false,
maxHeight = '500px',
enableMarkdown: _enableMarkdown = true,
enableFileUpload = false,
acceptedFileTypes = 'image/*,.pdf,.doc,.docx,.txt',
maxFileSize = 10 * 1024 * 1024,
suggestions,
labels,
models,
selectedModelId,
onModelChange,
headerSlot,
promptOverlaySlot,
onInputChange,
onToolApprove,
toolApproveLabel = 'Approve',
toolDenyLabel = 'Deny',
toolDenyReason = 'User denied the operation',
toolDecisions,
onReviewDraft,
toolReviewLabel = (n) => `Review ${n} change${n === 1 ? '' : 's'}`,
onPublishDrafts,
onOpenBuiltApp,
openBuiltAppLabel = 'Open app',
onPreviewDraftApp,
previewDraftLabel = 'Preview',
onDraftArtifacts,
onBuildMaterialized,
publishDraftsLabel = 'Publish',
publishedLabel = 'Published',
autoPublishDrafts = false,
processVisibility = 'summary',
surface = 'card',
...props
},
ref
) => {
const promptStatus: ChatStatus = isLoading ? 'streaming' : 'ready';
const isPlainSurface = surface === 'plain';
const [copiedId, setCopiedId] = React.useState<string | null>(null);
// Resolve localizable strings once, English defaults preserved.
const L = React.useMemo(
() => ({
emptyTitle: labels?.emptyTitle ?? 'Start a conversation',
emptyDescription:
labels?.emptyDescription ??
'Ask anything — the assistant has access to your current app context.',
clear: labels?.clear ?? 'Clear',
sendHint: labels?.sendHint ?? 'to send',
agentActivity: labels?.agentActivity ?? 'Agent activity',
toolCompleted: labels?.toolCompleted ?? 'Completed',
toolRunning: labels?.toolRunning ?? 'Running',
toolAwaitingApproval: labels?.toolAwaitingApproval ?? 'Awaiting approval',
toolFailed: labels?.toolFailed ?? 'Failed',
toolDetailsHidden:
labels?.toolDetailsHidden ??
'Detailed tool inputs and outputs are hidden in this view.',
copy: labels?.copy ?? 'Copy',
copied: labels?.copied ?? 'Copied',
regenerate: labels?.regenerate ?? 'Regenerate',
model: labels?.model ?? 'Model',
submit: labels?.submit ?? 'Submit',
uploadFiles: labels?.uploadFiles ?? 'Upload files',
stopResponse: labels?.stopResponse ?? 'Stop response',
trace: labels?.trace ?? 'trace',
viewTrace: labels?.viewTrace ?? 'View trace',
}),
[labels],
);
// Draft tool calls this chat has published (auto or via the manual button),
// so each card flips from a "Publish" button to a "Published" state instead
// of leaving a stale, now-meaningless button. Keyed by the draft's
// `toolCallId`, NOT its packageId: publishing a package promotes the drafts
// PENDING AT THAT MOMENT, but a later edit into the same package is a new,
// still-pending draft — it must NOT inherit the earlier build's "Published"
// badge (that would falsely tell the user an unpublished change is live).
const [publishedToolCalls, setPublishedToolCalls] = React.useState<ReadonlySet<string>>(
() => new Set(),
);
// ADR-0038 L3 — per published card, what the publish actually did at
// runtime (rows seeded, probes run, findings). Rendered under the
// Published badge as the build-health line.
const [publishHealthByToolCall, setPublishHealthByToolCall] = React.useState<
ReadonlyMap<string, PublishHealth>
>(() => new Map());
// Publish a package's drafts and reflect success on exactly the cards that
// were pending for it at publish time. The host's onPublishDrafts returns
// `false` / `{ok:false}` on failure (and surfaces its own error); any other
// outcome (incl. void) counts as success. A structured outcome may carry
// `health` (seedApplied + runtime probes) for the health line.
const handlePublishDrafts = React.useCallback(
async (packageId: string) => {
if (!onPublishDrafts) return;
// Snapshot the on-screen draft cards this publish will promote, BEFORE
// awaiting — later edits into the same package won't be in this set.
const promoted: string[] = [];
for (const message of messages) {
for (const tool of message.toolInvocations ?? []) {
if (tool.draftReview?.packageId === packageId && tool.toolCallId) {
promoted.push(tool.toolCallId);
}
}
}
const res = await onPublishDrafts(packageId);
const outcome: PublishOutcome | undefined =
res && typeof res === 'object' ? (res as PublishOutcome) : undefined;
const ok = outcome ? outcome.ok !== false : res !== false;
if (ok && promoted.length > 0) {
setPublishedToolCalls((prev) => {
const next = new Set(prev);
for (const id of promoted) next.add(id);
return next;
});
const health = outcome?.health;
if (health) {
setPublishHealthByToolCall((prev) => {
const next = new Map(prev);
for (const id of promoted) next.set(id, health);
return next;
});
}
}
},
[onPublishDrafts, messages],
);
// Auto-publish "magic moment": when the environment enables autoPublishDrafts
// and a WHOLE-APP build finishes (the backend marks it `autoPublishable`),
// fire the same publish-drafts call the manual button uses — objects go live
// and seed data loads, so the user lands on a populated, running app instead
// of hunting for Publish. Incremental edits are NOT auto-published: they omit
// `autoPublishable` and stay drafts for explicit review (a destructive edit
// must never go live silently). Drafts already on screen when the chat mounts
// are seeded as "seen" so reopening a conversation never republishes prior
// work; only NEW builds fire, each at most once, after streaming completes.
//
// Dedup is keyed by the draft tool's `toolCallId`, NOT its packageId: every
// build is a distinct tool call and several can target the SAME workspace
// package in one session. Keying by packageId would publish it only once and
// silently leave later builds staged. Keyed by toolCallId, each new build
// publishes its package once (publish-drafts only promotes rows still
// pending, so re-publishing a package is safe).
const autoPublishedRef = React.useRef<Set<string>>(new Set());
const autoPublishSeededRef = React.useRef(false);
React.useEffect(() => {
const builds: Array<{ key: string; packageId: string }> = [];
for (const message of messages) {
for (const tool of message.toolInvocations ?? []) {
const dr = tool.draftReview;
if (dr?.autoPublishable && dr.packageId && tool.toolCallId && dr.items.length > 0) {
builds.push({ key: tool.toolCallId, packageId: dr.packageId });
}
}
}
if (!autoPublishSeededRef.current) {
autoPublishSeededRef.current = true;
for (const b of builds) autoPublishedRef.current.add(b.key);
return;
}
// Wait for the turn to finish so we publish the complete build once.
if (!autoPublishDrafts || !onPublishDrafts || isLoading) return;
const fresh = builds.filter((b) => !autoPublishedRef.current.has(b.key));
if (fresh.length === 0) return;
for (const b of fresh) autoPublishedRef.current.add(b.key);
// One publish per distinct package, even if a turn made several build calls.
for (const pkg of [...new Set(fresh.map((b) => b.packageId))]) void handlePublishDrafts(pkg);
}, [messages, isLoading, autoPublishDrafts, onPublishDrafts, handlePublishDrafts]);
// ADR-0037 Live Canvas: surface every AI-authored draft artifact to the
// host as it lands — both the streaming build tree's items and drafted
// envelopes. Deduped cumulatively; the callback fires only when the set
// actually grows, so hosts can refresh a preview pane without storms.
const draftArtifactKeysRef = React.useRef<Set<string>>(new Set());
React.useEffect(() => {
if (!onDraftArtifacts) return;
const artifacts = new Map<string, { type: string; name: string }>();
for (const message of messages) {
for (const item of message.buildProgress?.items ?? []) {
if (item?.type && item?.name) artifacts.set(`${item.type}:${item.name}`, item);
}
for (const tool of message.toolInvocations ?? []) {
for (const item of tool.draftReview?.items ?? []) {
if (item?.type && item?.name) artifacts.set(`${item.type}:${item.name}`, item);
}
}
}
const seen = draftArtifactKeysRef.current;
let grew = false;
for (const key of artifacts.keys()) {
if (!seen.has(key)) {
seen.add(key);
grew = true;
}
}
if (grew) onDraftArtifacts([...artifacts.values()]);
}, [messages, onDraftArtifacts]);
// ADR-0045: announce materialized builds (real app live, unlisted) so the
// host flips its canvas from the draft overlay to the real app URL. Once
// per build (keyed by toolCallId), including on conversation reload —
// a reopened materialized build should still preview the real app.
const materializedKeysRef = React.useRef<Set<string>>(new Set());
React.useEffect(() => {
if (!onBuildMaterialized) return;
for (const message of messages) {
for (const tool of message.toolInvocations ?? []) {
const dr = tool.draftReview;
if (!dr?.materialized || !tool.toolCallId) continue;
const app = dr.items.find((i) => i.type === 'app');
if (!app || materializedKeysRef.current.has(tool.toolCallId)) continue;
materializedKeysRef.current.add(tool.toolCallId);
onBuildMaterialized(app.name);
}
}
}, [messages, onBuildMaterialized]);
const handleSubmit = React.useCallback(
(payload: PromptInputMessage) => {
const hasText = Boolean(payload.text?.trim());
const files = payload.files
?.map((f) => (f as unknown as { file?: File }).file)
.filter(Boolean) as File[] | undefined;
const hasFiles = Boolean(files && files.length > 0);
if (!(hasText || hasFiles)) return;
onSendMessage?.(payload.text?.trim() ?? '', files);
},
[onSendMessage]
);
const handleSuggestionClick = React.useCallback(
(text: string) => {
onSendMessage?.(text);
},
[onSendMessage]
);
const handleCopy = React.useCallback((message: ChatMessage) => {
void navigator.clipboard?.writeText(message.content);
setCopiedId(message.id);
window.setTimeout(() => setCopiedId((prev) => (prev === message.id ? null : prev)), 1500);
}, []);
const renderToolDetail = (tool: ChatToolInvocation) => {
const state =
tool.state ??
(tool.errorText
? 'output-error'
: tool.result !== undefined
? 'output-available'
: 'input-available');
const partType = `tool-${tool.toolName}` as `tool-${string}`;
const decision = toolDecisions?.[tool.toolCallId];
const isAwaitingApproval =
state === 'approval-requested' && Boolean(onToolApprove) && !decision;
const hidePendingPayload =
state === 'approval-requested' && Boolean(tool.pendingActionId);
const friendlyTitle = humanizeToolName(tool.toolName);
const renderableResult = unwrapToolResult(tool.result);
const showRawName =
processVisibility === 'debug' &&
friendlyTitle &&
friendlyTitle.toLowerCase() !== tool.toolName.toLowerCase();
// Raw PARAMETERS/RESULT JSON is developer detail — only in `debug` mode,
// or when a HITL approval needs the operator to see the exact payload.
// A drafting tool (create_object / apply_blueprint) is NOT a reason to dump
// JSON: the human summary + the Publish/Review affordance below already tell
// a Build-with-AI user what happened, so on the consumer surface (`summary`)
// the whole-app blueprint JSON and "status: drafted" envelopes stay hidden.
const showPayload =
processVisibility === 'debug' ||
isAwaitingApproval;
const titleNode = (
<span className="inline-flex items-center gap-2">
<span>{friendlyTitle || tool.toolName}</span>
{showRawName ? (
<code className="rounded bg-muted px-1 py-px text-[10px] font-mono text-muted-foreground">
{tool.toolName}
</code>
) : null}
</span>
);
return (
<Tool
key={tool.toolCallId}
defaultOpen={
state === 'output-error' ||
state === 'approval-requested' ||
Boolean(tool.draftReview && tool.draftReview.items.length > 0)
}
>
<ToolHeader type={partType} state={state} title={titleNode} />
<ToolContent>
{showPayload && tool.args !== undefined ? (
<ToolInput input={tool.args} />
) : null}
{hidePendingPayload ? null : showPayload || state === 'output-error' ? (
<SmartToolOutput
output={renderableResult}
errorText={tool.errorText}
/>
) : null}
{decision ? (
<div
className={
'flex items-center gap-2 p-3 border-t text-xs ' +
(decision.state === 'error'
? 'bg-destructive/10 text-destructive'