-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathChatPane.tsx
More file actions
4491 lines (4331 loc) · 174 KB
/
Copy pathChatPane.tsx
File metadata and controls
4491 lines (4331 loc) · 174 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
import {
Fragment,
memo,
useCallback,
useDeferredValue,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type CSSProperties,
type DragEvent as ReactDragEvent,
type MutableRefObject,
type ReactNode,
} from 'react';
import { createPortal } from 'react-dom';
import { hasOdCard } from '@open-design/contracts';
import { useAnalytics } from '../analytics/provider';
import { getResolvedDeviceId } from '../analytics/client';
import { trackChatPanelClick, trackMessageQueueClick, trackRunFailedToastSurfaceView } from '../analytics/events';
import { amrHandoffDeviceId, attributedAmrUrl, recordAmrEntry } from '../analytics/amr-attribution';
import { useT } from '../i18n';
import { startersForProduct, type ProductType } from '../onboarding/recommendation';
import { starterCopyFor } from '../onboarding/starter-copy';
import {
FEATURED_DESIGN_TOOLBOX_ACTION_IDS,
findDesignToolboxSkill,
getDesignToolboxAction,
type DesignToolboxActionId,
} from '../runtime/design-toolbox';
import { isRetryableAssistantTerminalFailure } from '../runtime/design-delivery';
import type { Dict } from '../i18n/types';
import { copyToClipboard } from '../lib/copy-to-clipboard';
import { projectRawUrl } from '../providers/registry';
import { takeComposerSeedFor } from '../state/libraryHandoff';
import { splitOnQuestionForms } from '../artifacts/question-form';
import { stripArtifact } from '../artifacts/strip';
import type { TodoItem } from '../runtime/todos';
import type {
AppliedPluginSnapshot,
ChatSessionMode,
RunContextSelection,
WorkspaceContextItem,
} from '@open-design/contracts';
import type { TrackingProjectKind } from '@open-design/contracts/analytics';
import {
DESIGN_SYSTEM_WORKSPACE_DISPLAY_DESCRIPTION,
DESIGN_SYSTEM_WORKSPACE_DISPLAY_TITLE,
isDesignSystemWorkspacePrompt,
} from '../design-system-auto-prompt';
import {
isTodoWriteToolName,
latestTodoWriteInputForPinnedCard,
unfinishedTodosFromEvents,
} from '../runtime/todos';
import type { AppConfig, ChatAttachment, ChatCommentAttachment, ChatMessage, ChatMessageFeedbackChange, Conversation, DesignSystemSummary, PreviewComment, Project, ProjectFile, ProjectMetadata, SkillSummary } from '../types';
import { agentDisplayName } from '../utils/agentLabels';
import { commentTargetDisplayName, commentsToAttachments, simplePositionLabel } from '../comments';
import { AssistantMessage, type QuestionFormSubmitHandler } from './AssistantMessage';
import { TodoCard } from './ToolCard';
import type { BrandBrowserAssistConfirm } from './OdCard';
import {
DESIGN_SYSTEM_NEXT_STEP_ACTIONS,
type NextStepActionsVariant,
} from './NextStepActions';
import { AmrGuidance } from './AmrGuidance';
import { AmrLoginPill } from './AmrLoginPill';
import {
AMR_LOGIN_STATUS_EVENT,
amrLoginStatusEventReason,
} from './amrLoginPolling';
import {
amrPlansUrlForProfile,
amrRechargeUrlForProfile,
resolveRunFailureUi,
} from '../runtime/amr-guidance';
import {
fetchVelaLoginStatus,
type VelaLoginStatus,
} from '../providers/daemon';
import { RESUME_CONTINUE_PROMPT } from '../runtime/resume';
import {
ChatComposer,
type ChatComposerHandle,
type ChatSendOutcome,
type ChatSendMeta,
} from './ChatComposer';
import type { PlaceholderScenario } from './home-hero/placeholderScenarios';
import { listDesignArtifactCandidates } from './design-files/designArtifacts';
import type { PluginFolderAgentAction } from './design-files/pluginFolderActions';
import { Icon, type IconName } from './Icon';
import { UserActionCard, type UserActionCardTone } from './UserActionCard';
import { repoConnectCopy } from './design-system-github-evidence';
import { isRenderableSketchJson, SketchPreview } from './SketchPreview';
import type { SettingsSection } from './SettingsDialog';
type TranslateFn = (key: keyof Dict, vars?: Record<string, string | number>) => string;
// Featured starter prompts shown on the empty chat. Clicking one fills
// the composer (does not auto-send) so users can tweak before sending.
// Each prompt is intentionally dense — it should showcase ambitious
// layout, typographic, and information-design moves rather than a
// generic landing page.
//
// Starter sets are picked per project kind (and per video model) so a
// fresh seedance video, a hyperframes html-in-canvas video, an image
// project and an audio project each see relevant prompts instead of the
// generic starter set. The default (prototype/deck/template/other/
// live-artifact) set stays i18n-translated via existing chat.example*
// keys so the user-facing copy keeps its localizations. The new media
// sets are inline English literals — they are technical agent prompts
// that work well across locales without translation, and going through
// i18n for each of them would balloon every Dict entry by 12+ keys.
type StarterPrompt = {
icon: string;
title: string;
// Empty for path-scoped onboarding starters, which have no category tag.
tag: string;
prompt: string;
};
const DEFAULT_STARTER_KEYS: Array<{
icon: string;
titleKey: keyof Dict;
tagKey: keyof Dict;
promptKey: keyof Dict;
}> = [
{
icon: '▤',
titleKey: 'chat.example1Title',
tagKey: 'chat.example1Tag',
promptKey: 'chat.example1Prompt',
},
{
icon: '▦',
titleKey: 'chat.example2Title',
tagKey: 'chat.example2Tag',
promptKey: 'chat.example2Prompt',
},
{
icon: '◈',
titleKey: 'chat.example3Title',
tagKey: 'chat.example3Tag',
promptKey: 'chat.example3Prompt',
},
{
icon: '▶',
titleKey: 'chat.example4Title',
tagKey: 'chat.example4Tag',
promptKey: 'chat.example4Prompt',
},
];
const IMPORTED_ARTIFACTS_INITIAL_VISIBLE_COUNT = 5;
const IMPORTED_ARTIFACTS_REVEAL_COUNT = 5;
const IMAGE_STARTERS: StarterPrompt[] = [
{
icon: '◯',
title: 'Editorial portrait',
tag: 'Portrait',
prompt:
'A close-up editorial portrait of a young creative director in their late 20s, soft natural light through tall studio windows, warm neutral palette (cream, taupe, soft black), shot at 85mm f/1.8 with shallow depth of field, sharp gaze straight to camera, subtle film grain, no makeup look.',
},
{
icon: '▭',
title: 'Product hero',
tag: 'E-commerce',
prompt:
'A premium product hero shot of a single matte ceramic coffee mug on a warm cream paper backdrop. Hard rim light from the upper-left, gentle elongated shadow stretching to the lower-right, faint steam rising from the cup. Square crop, centered composition, room above for headline copy, no props or hands in frame.',
},
{
icon: '◐',
title: 'Flat illustration',
tag: 'Illustration',
prompt:
'A flat vector illustration of a cozy reading nook by a rainy window — geometric shapes, restrained 5-color palette (cream, terracotta, deep teal, burnt sienna, soft black), thin 1.5px line accents, no gradients, no textures, soft drop shadows only on the foreground armchair.',
},
];
// Pure-video / cinematic-shot starters for seedance, sora, kling, veo,
// grok-imagine and similar text-to-video models. Each prompt is one
// shot, restrained motion, and a clear visual concept the model can
// nail in 5-10 seconds.
const VIDEO_SEEDANCE_STARTERS: StarterPrompt[] = [
{
icon: '◉',
title: 'Product reveal',
tag: 'Cinematic',
prompt:
'A 5-second product reveal: a minimal high-end skincare bottle on a clean cream stone surface, soft side light from camera-left, slow camera push-in, subtle depth-of-field shift from the cap to the label, restrained motion, no text overlays, no people in frame.',
},
{
icon: '▣',
title: 'Lantern close-up',
tag: 'Mood',
prompt:
'A 6-second cinematic close-up of a young woman holding a glowing paper lantern in a misty pine forest at golden hour. Shallow depth of field on her eyes, gentle dolly-in, ambient particles drifting through the warm shaft of light, no dialogue, ambient forest sound only.',
},
{
icon: '⌘',
title: 'Neon street drift',
tag: 'Action',
prompt:
'A 5-second street-racing tracking shot at night in a neon-lit cyberpunk Hong Kong alley. Low-angle camera following a matte-black sports car drifting around a tight corner, motion blur on the wheels, lens flares from oncoming neon signs, rain-slick asphalt reflecting the lights, no on-screen text.',
},
];
// HyperFrames HTML-in-canvas starters — these target the
// hyperframes-html video model where the renderer captures live DOM
// into a WebGL texture and runs shader effects on top. References:
// https://www.remotion.dev/docs/html-in-canvas (concept), the seven
// vfx-* catalog blocks shipped via `npx hyperframes add vfx-*`, and
// skills/hyperframes/references/html-in-canvas.md.
const VIDEO_HYPERFRAMES_STARTERS: StarterPrompt[] = [
{
icon: '◉',
title: 'Magnifying glass reveal',
tag: 'HTML-in-canvas',
prompt:
'Make a 5-second composition with a single line of bold display text on a clean canvas. Animate a round magnifying glass that travels left to right across the line, with subtle glass refraction warping the letters underneath as it passes. Use HyperFrames html-in-canvas — capture the text DOM and run the lens shader on top via a vfx-liquid-glass-style pass. Pure CSS for the text; the glass is a WebGL layer.',
},
{
icon: '▦',
title: 'CRT terminal scene',
tag: 'Vintage VFX',
prompt:
"Make a CRT-screen composition: dark canvas, monospace terminal text typing `npx hyperframes init my-video`, then `claude` invoked with the prompt 'Add a CRT effect using HTML-in-canvas'. Apply a subtle convex-curvature shader, scanlines, slight chromatic aberration, and a soft phosphor glow on top of the live DOM via html-in-canvas. The terminal text stays as real CSS so it's pixel-sharp before the shader pass.",
},
{
icon: '◈',
title: 'Glitch breakdown',
tag: 'Glitch',
prompt:
'Build a 6-second composition that displays a hero headline and a one-line subhead on a dark canvas, then breaks into a hard digital glitch — RGB channel split, horizontal displacement bands, brief frame-stutter, and a final clean reset. Capture the live DOM via html-in-canvas and run the glitch pass on top, so the type is real CSS underneath the shader.',
},
];
// Speech-focused audio starters — the New Project audio panel only
// surfaces the `speech` kind today (see MediaProjectOptions), so we
// match that. If/when the music + sfx tabs come back, broaden this set.
const AUDIO_STARTERS: StarterPrompt[] = [
{
icon: '♪',
title: 'Brand voiceover',
tag: 'Speech',
prompt:
"A 30-second warm-toned narrative voiceover for a product launch video — confident but conversational, mid-tempo, with a beat of pause after the brand name. Script: 'Three years in the making. One simple promise. Meet [product name] — the way work was supposed to feel.' English, neutral North American accent.",
},
{
icon: '♫',
title: 'Onboarding narration',
tag: 'Speech',
prompt:
"A 20-second friendly onboarding narration for a mobile app's first-launch screen. Reassuring, smiling tone, slow enough to feel attentive without sounding scripted. Script: 'Welcome to Loop. Let's set up your space — three quick questions and you're in. You can change any of this later.'",
},
{
icon: '♬',
title: 'Story passage read',
tag: 'Speech',
prompt:
"A 45-second cinematic read of an opening passage. Low, measured delivery with breath between sentences, slightly intimate close-mic'd quality. Script: 'The city sleeps in pieces. A neon sign flickers above the ramen counter. Across the avenue, a window glows — the only one still on this side of midnight.'",
},
];
function pickStarters(
metadata: ProjectMetadata | undefined,
t: TranslateFn,
): StarterPrompt[] {
const kind = metadata?.kind;
if (kind === 'image') return IMAGE_STARTERS;
if (kind === 'video') {
return metadata?.videoModel === 'hyperframes-html'
? VIDEO_HYPERFRAMES_STARTERS
: VIDEO_SEEDANCE_STARTERS;
}
if (kind === 'audio') return AUDIO_STARTERS;
return DEFAULT_STARTER_KEYS.map((entry) => ({
icon: entry.icon,
title: t(entry.titleKey),
tag: t(entry.tagKey),
prompt: t(entry.promptKey),
}));
}
function sortArtifactsByModified(files: ProjectFile[]): ProjectFile[] {
return [...files].sort(
(a, b) => b.mtime - a.mtime || a.name.localeCompare(b.name),
);
}
function ImportedFolderArtifacts({
projectId,
files,
onOpenFile,
t,
}: {
projectId: string | null;
files: ProjectFile[];
onOpenFile?: (name: string) => void;
t: TranslateFn;
}) {
const [visibleCount, setVisibleCount] = useState(IMPORTED_ARTIFACTS_INITIAL_VISIBLE_COUNT);
useEffect(() => {
setVisibleCount(IMPORTED_ARTIFACTS_INITIAL_VISIBLE_COUNT);
}, [files]);
if (files.length === 0) {
return (
<div className="chat-design-artifacts-empty" data-testid="chat-design-artifacts-empty">
{t('designFiles.empty')}
</div>
);
}
const visibleFiles = files.slice(0, visibleCount);
const hiddenCount = Math.max(0, files.length - visibleFiles.length);
const revealCount = Math.min(IMPORTED_ARTIFACTS_REVEAL_COUNT, hiddenCount);
const revealLabel = t('chat.designArtifactsShowMore', { count: revealCount });
return (
<div className="chat-design-artifacts" data-testid="chat-design-artifacts">
{visibleFiles.map((file, index) => {
const openable = Boolean(onOpenFile);
const openLabel = `${t('designFiles.previewOpen')} ${file.name}`;
const openFile = () => {
onOpenFile?.(file.name);
};
return (
<div
key={file.name}
className="chat-design-artifact"
data-kind={file.kind}
data-file-name={file.name}
data-testid={`chat-design-artifact-${index}`}
role={openable ? 'button' : 'listitem'}
tabIndex={openable ? 0 : undefined}
title={openLabel}
aria-label={openLabel}
onDoubleClick={openable ? openFile : undefined}
onKeyDown={
openable
? (event) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
openFile();
}
: undefined
}
>
<div className="chat-design-artifact-preview" aria-hidden>
<ChatArtifactPreview projectId={projectId} file={file} />
</div>
<div className="chat-design-artifact-meta">
<span className="chat-design-artifact-name" title={file.name}>
{file.name}
</span>
<span className="chat-design-artifact-kind">
{chatArtifactKindLabel(file.kind, t)}
</span>
</div>
</div>
);
})}
{hiddenCount > 0 ? (
<button
type="button"
className="chat-design-artifact chat-design-artifact-more"
data-testid="chat-design-artifacts-more"
aria-label={revealLabel}
title={revealLabel}
onClick={() => {
setVisibleCount((current) =>
Math.min(files.length, current + IMPORTED_ARTIFACTS_REVEAL_COUNT),
);
}}
>
<span className="chat-design-artifact-more-icon" aria-hidden>
+
</span>
<span className="chat-design-artifact-more-count">
{revealLabel}
</span>
</button>
) : null}
</div>
);
}
function ChatArtifactPreview({
projectId,
file,
}: {
projectId: string | null;
file: ProjectFile;
}) {
if (!projectId) {
return <ChatArtifactFallback kind={file.kind} />;
}
const url = `${projectRawUrl(projectId, file.name)}?v=${Math.round(file.mtime)}`;
if (isRenderableSketchJson(file)) {
return <SketchPreview projectId={projectId} file={file} />;
}
if (file.kind === 'image' || file.kind === 'sketch') {
return <img src={url} alt="" loading="lazy" />;
}
if (file.kind === 'html') {
return (
<iframe
title={file.name}
src={url}
sandbox="allow-scripts allow-downloads"
loading="lazy"
/>
);
}
if (file.kind === 'video') {
return <video src={url} muted playsInline preload="metadata" />;
}
return <ChatArtifactFallback kind={file.kind} />;
}
function ChatArtifactFallback({ kind }: { kind: ProjectFile['kind'] }) {
return (
<span className="chat-design-artifact-fallback">
<Icon name={chatArtifactIcon(kind)} size={28} />
<span>{chatArtifactShortKind(kind)}</span>
</span>
);
}
function chatArtifactIcon(kind: ProjectFile['kind']): IconName {
if (kind === 'html' || kind === 'code') return 'file-code';
if (kind === 'image' || kind === 'sketch') return 'image';
if (kind === 'video' || kind === 'audio') return 'play';
if (kind === 'presentation') return 'present';
return 'file';
}
function chatArtifactShortKind(kind: ProjectFile['kind']): string {
if (kind === 'html') return 'HTML';
if (kind === 'image') return 'IMG';
if (kind === 'sketch') return 'SKETCH';
if (kind === 'video') return 'VIDEO';
if (kind === 'pdf') return 'PDF';
if (kind === 'presentation') return 'PPT';
if (kind === 'document') return 'DOC';
return 'FILE';
}
function chatArtifactKindLabel(kind: ProjectFile['kind'], t: TranslateFn): string {
if (kind === 'html') return t('designFiles.kindHtml');
if (kind === 'image') return t('designFiles.kindImage');
if (kind === 'sketch') return t('designFiles.kindSketch');
if (kind === 'video') return 'Video';
if (kind === 'audio') return 'Audio';
if (kind === 'pdf') return t('designFiles.kindPdf');
if (kind === 'document') return t('designFiles.kindDocument');
if (kind === 'presentation') return t('designFiles.kindPresentation');
if (kind === 'spreadsheet') return t('designFiles.kindSpreadsheet');
return t('designFiles.kindBinary');
}
interface Props {
messages: ChatMessage[];
streaming: boolean;
loading?: boolean;
error: string | null;
projectId: string | null;
sessionMode?: ChatSessionMode;
onSessionModeChange?: (mode: ChatSessionMode) => void;
// Analytics-only — forwarded to AssistantMessage so the feedback
// events know which project surface the rating applies to. Optional
// (defaults to null/'prototype') so unit tests can mount ChatPane
// without project context.
projectKindForTracking?: TrackingProjectKind | null;
projectFiles: ProjectFile[];
activeProjectFileName?: string | null;
hasActiveDesignSystem?: boolean;
activeDesignSystem?: DesignSystemSummary | null;
sendDisabled?: boolean;
queuedItems?: QueuedSendItem[];
onRemoveQueuedSend?: (id: string) => void;
onUpdateQueuedSend?: (id: string, update: QueuedSendUpdate) => void;
onReorderQueuedSends?: (orderedIds: string[]) => void;
onSendQueuedNow?: (id: string) => void;
// Names that exist in the project folder. Tool cards and chips use this
// set to decide whether a path can be opened as a tab.
projectFileNames?: Set<string>;
// Daemon-resolved on-disk working directory of the current project —
// positive-proof anchor for chat file-link routing (see AssistantMessage).
projectResolvedDir?: string | null;
onEnsureProject: () => Promise<string | null>;
previewComments?: PreviewComment[];
attachedComments?: PreviewComment[];
onAttachComment?: (comment: PreviewComment) => void;
onDetachComment?: (commentId: string) => void;
onDeleteComment?: (commentId: string) => void;
onSend: (
prompt: string,
attachments: ChatAttachment[],
commentAttachments: ChatCommentAttachment[],
meta?: ChatSendMeta,
) => ChatSendOutcome | Promise<ChatSendOutcome>;
onRetry?: (assistantMessage: ChatMessage) => void;
onResumeRun?: (assistantMessage: ChatMessage) => void;
onStop: () => void;
// Skills available for @-mention assembly. ProjectView filters out the
// user's disabled set before passing them in here.
skills?: SkillSummary[];
// Click-to-open chain: passes a basename up to ProjectView, which sets
// FileWorkspace's openRequest. Tool cards, attachment chips, and
// produced-file chips all call this.
onRequestOpenFile?: (name: string) => void;
onRequestPluginDetails?: (pluginId: string) => void;
onRequestDesignSystemDetails?: (system: DesignSystemSummary) => void;
onRequestPluginFolderAgentAction?: (
relativePath: string,
action: PluginFolderAgentAction,
) => Promise<{ message?: string; url?: string } | void> | { message?: string; url?: string } | void;
activePluginActionPaths?: Set<string>;
hiddenPluginActionPaths?: Set<string>;
// "Share to Open Design" button on each completed assistant message —
// wired by ProjectView to handleSend with the bundled
// `od-share-to-community` scenario's trigger prompt.
onShareToOpenDesign?: (assistantMessageId: string) => void;
shareToOpenDesignBusyMessageId?: string | null;
forceStreamingMessageIds?: Set<string>;
// Live-only streaming tool-input partials keyed by tool-use id. Threaded to
// AssistantMessage so an in-flight Write/Edit can render its code in real
// time before the full `tool_use` arrives. Never persisted.
liveToolInput?: Record<string, { name: string; text: string; seq?: number }>;
initialDraft?: string;
// Product path of the Home recommendation that started this project. When
// set (and concrete), the empty-conversation starter cards show that path's
// starters — one-click composer replacements — instead of the generic set.
onboardingStarterPath?: ProductType | null;
composerPlaceholder?: string;
onSubmitQuestionForm?: QuestionFormSubmitHandler;
questionFormSubmitDisabled?: boolean;
onContinueRemainingTasks?: (
assistantMessage: ChatMessage,
todos: TodoItem[],
) => boolean | void | Promise<boolean | void>;
onAssistantFeedback?: (assistantMessage: ChatMessage, change: ChatMessageFeedbackChange) => void;
// Client-side action for a brand-browser-assist od-card: open/focus the
// Browser tab. Routed through the stable callbacks ref.
onBrandBrowserAssistConfirm?: BrandBrowserAssistConfirm;
// "Next step" affordance handlers forwarded to the last assistant message.
// The featured design-toolbox rows are driven directly off the composer ref
// owned here, so they need no handler from ProjectView (unlike onArtifactShare).
onArtifactShare?: (fileName: string) => void;
onArtifactDownload?: (fileName: string) => void;
onForkFromMessage?: (assistantMessage: ChatMessage) => void;
forkingMessageId?: string | null;
// Header "+" button — kicks off ProjectView's create-conversation flow.
onNewConversation?: () => void;
newConversationDisabled?: boolean;
// Conversation list that used to live in the topbar. The chat tab now
// owns the list so users can browse + switch conversations without
// leaving the pane.
conversations: Conversation[];
activeConversationId: string | null;
// The conversation whose history the live `messages` array currently
// reflects. Null while a switch is mid-flight (or after a load failure),
// which is exactly when `messages.length` must NOT be trusted as the active
// conversation's count — see `conversationMessageCount`. Callers that do not
// track this (mounts whose loader resets/retags `messages` asynchronously)
// leave it undefined and fall back to the persisted `conversation.messageCount`
// for a stable list count.
messagesConversationId?: string | null;
onSelectConversation: (id: string) => void;
onDeleteConversation: (id: string) => void;
// Composer settings/CLI button forwards to here. The dialog lives in App
// (it owns the AppConfig lifecycle) so we just pass the open trigger.
onOpenSettings?: (section?: SettingsSection) => void;
showByokRecoveryAction?: boolean;
onSwitchToLocalCli?: () => void;
onOpenAmrSettings?: () => void;
onSwitchToAmrAndRetry?: (failedAssistant: ChatMessage) => void;
// PR #3157: Antigravity's `agy -p` can't complete OAuth on its own,
// so the auth banner offers a "Sign in via terminal" button that
// POSTs to /api/agents/antigravity/oauth-launch. Handler resolves
// after the daemon kicks off `osascript`/`x-terminal-emulator`/
// `cmd /c start` so the UI can disable the button while in flight.
onLaunchAntigravityOauth?: () => Promise<void>;
// Same dialog, but landing on the External MCP tab. Forwarded to the
// composer's `/mcp` slash and MCP picker button.
onOpenMcpSettings?: () => void;
// The composer "+" menu's "add plugin" / "add connector" rows route to the
// home plugin-registry / connector-integration surfaces.
onBrowsePlugins?: () => void;
onOpenConnectors?: () => void;
// True when this project is a GitHub-backed design system whose repository
// evidence has not fully landed. Surfaces a "Connect your repo" CTA in the
// empty chat state alongside the starter examples.
connectRepoNeeded?: boolean;
// Live GitHub connector status, used only to pick the connect-repo CTA copy
// (connect vs re-import). Undefined until the status fetch resolves.
githubConnected?: boolean;
// Fires when the connect-repo CTA button is clicked. The parent decides what
// it does based on connector status (open Connectors, or prefill the composer
// with the import instruction).
onConnectRepo?: () => void;
// True once the deterministic brand extraction actually reached ready. Until
// then the next-step card must stay on continue/recover actions even if the
// latest assistant row is terminal.
brandExtractionComplete?: boolean;
// True for a programmatically-extracted brand project whose AI enrichment
// never ran. The next-step card uses this to offer AI Optimize after the
// extraction completion message.
brandEnrichmentEligible?: boolean;
// Runs the optional brand-enrichment turn. The parent sends the project's
// seeded enrichment prompt with the default per-turn skill bundle.
onContinueBrandEnrichment?: () => void;
brandEnrichmentBusy?: boolean;
// Runs or resumes the selected agent for an incomplete brand extraction
// scaffold. Distinct from AI Optimize, which assumes a ready system exists.
onContinueBrandAgentExtraction?: () => void;
continueBrandAgentExtractionBusy?: boolean;
// Restarts the deterministic programmatic pass for an incomplete brand
// extraction without creating a duplicate design-system item.
onContinueBrandExtraction?: () => void;
continueBrandExtractionBusy?: boolean;
// Creates a fresh design project using the current extracted design system.
onCreateDesignFromActiveDesignSystem?: () => void;
createDesignFromActiveDesignSystemBusy?: boolean;
// Duplicates a regular project into a new design-system workspace and starts
// the design-system generation pass from that copied evidence.
onCreateDesignSystemFromProject?: () => void;
createDesignSystemFromProjectBusy?: boolean;
// Bumped by the parent to push a draft into the composer (used by the
// "Import repo" CTA). The nonce lets the same text fire more than once.
composerDraftSignal?: { text: string; nonce: number };
// Optional pet wiring forwarded straight through to ChatComposer's
// /pet button. When omitted the composer hides the button entirely.
petConfig?: AppConfig['pet'];
onAdoptPet?: (petId: string) => void;
onTogglePet?: () => void;
onOpenPetSettings?: () => void;
projectMetadata?: ProjectMetadata;
// Authoritative post-patch project from the daemon — see ChatComposer's
// prop of the same name for the recency invariant.
onProjectMetadataChange?: (updated: Project) => void;
activeWorkspaceContext?: WorkspaceContextItem | null;
initialWorkspaceContexts?: WorkspaceContextItem[];
workspaceContexts?: WorkspaceContextItem[];
currentSkillId?: string | null;
onProjectSkillChange?: (skillId: string | null) => void;
researchAvailable?: boolean;
// Immutable snapshot of the plugin pinned to this project. When set
// we suppress the in-composer plugin rail (the user already picked a
// plugin on Home) and render the active plugin as a context chip on
// each user message — that satisfies §8 "show context inside the run
// message" without forcing a separate side widget.
activePluginSnapshot?: AppliedPluginSnapshot | null;
// SenseAudio BYOK only — wired straight through to ChatComposer for the
// in-composer image-model picker. Active protocol is read so the picker
// hides when the user is on any other BYOK tab (azure / openai / …).
byokApiProtocol?: AppConfig['apiProtocol'];
byokImageModel?: string;
onChangeByokImageModel?: (model: string) => void;
byokVideoModel?: string;
onChangeByokVideoModel?: (model: string) => void;
byokSpeechModel?: string;
onChangeByokSpeechModel?: (model: string) => void;
byokSpeechVoice?: string;
onChangeByokSpeechVoice?: (voice: string) => void;
composerFooterAccessory?: ReactNode;
// Slot rendered next to the composer's "+" menu (e.g. the working-dir pill).
composerLeadingAccessory?: ReactNode;
// Forwarded straight to the chat composer's mid-chat design-system
// switcher. ProjectView owns the project record so the parent is the
// natural place to mirror the patched project after a PATCH lands.
currentDesignSystemId?: string | null;
onActiveDesignSystemChange?: (project: Project) => void;
onShowToast?: (message: string) => void;
// Optional transient UI owned by the project shell. Rendering it inside the
// scroll-area wrapper keeps it structurally above the variable-height
// composer instead of guessing a bottom offset from outside ChatPane.
chatLogTray?: ReactNode;
// Project header slot. The former standalone chrome header row was removed;
// its back button, project title (editable) and design-system picker moved
// into the top of the chat pane. ProjectView owns the project record so it
// renders these as slots rather than ChatPane re-deriving the data.
onBack?: () => void;
backLabel?: string;
projectHeader?: ReactNode;
designSystemPicker?: ReactNode;
config?: AppConfig;
}
const AMR_PROFILE_ENV_KEY = 'OPEN_DESIGN_AMR_PROFILE';
type Tab = 'chat' | 'comments';
const CHAT_MESSAGE_VIRTUALIZE_THRESHOLD = 80;
const CHAT_MESSAGE_OVERSCAN_PX = 900;
const CHAT_VIRTUAL_ROW_GAP_PX = 14;
const CHAT_VIRTUAL_MIN_ROW_HEIGHT = 36;
const CHAT_VIRTUAL_DEFAULT_VIEWPORT_PX = 640;
const CHAT_VIRTUAL_INITIAL_TAIL_ROWS = 16;
const CONVERSATION_ROW_HEIGHT_PX = 34;
const CONVERSATION_VIRTUALIZE_THRESHOLD = 36;
const CONVERSATION_OVERSCAN_ROWS = 8;
interface RunErrorDiagnosticInput {
message: string;
rawMessage?: string | null;
errorCode?: string;
traceId?: string;
projectId?: string | null;
conversationId?: string | null;
assistantMessageId?: string;
agentId?: string;
}
interface QueuedSendItem {
id: string;
prompt: string;
attachments?: ChatAttachment[];
commentAttachments?: ChatCommentAttachment[];
meta?: ChatSendMeta;
}
interface QueuedSendUpdate {
prompt: string;
attachments: ChatAttachment[];
commentAttachments: ChatCommentAttachment[];
meta?: ChatSendMeta;
}
// Gap left above the anchored user message when it is pinned to the top.
const ANCHOR_TOP_PADDING = 12;
function shouldHideEmptyBrandAssistantMessage(message: ChatMessage, metadata?: ProjectMetadata): boolean {
if (metadata?.importedFrom !== 'brand-extraction' && metadata?.kind !== 'brand') return false;
if (message.role !== 'assistant') return false;
if (brandAssistantTextHasVisibleContent(message.content)) return false;
if ((message.events ?? []).some(hasVisibleBrandAssistantEvent)) return false;
if ((message.producedFiles?.length ?? 0) > 0) return false;
return Boolean(message.runStatus || message.endedAt);
}
function brandAssistantTextHasVisibleContent(content: string): boolean {
const trimmed = content.trim();
if (!trimmed) return false;
if (hasOdCard(trimmed)) return true;
const withoutArtifacts = stripArtifact(trimmed).trim();
if (!withoutArtifacts) return false;
return splitOnQuestionForms(withoutArtifacts).some((segment) => {
if (segment.kind === 'form') return true;
return segment.text.trim().length > 0;
});
}
const HIDDEN_BRAND_ASSISTANT_STATUS_LABELS = new Set([
'streaming',
'starting',
'running',
'requesting',
'thinking',
'empty_response',
'done',
'completed',
]);
function hasVisibleBrandAssistantEvent(event: NonNullable<ChatMessage['events']>[number]): boolean {
switch (event.kind) {
case 'text':
return brandAssistantTextHasVisibleContent(event.text);
case 'thinking':
return event.text.trim().length > 0;
case 'tool_use':
case 'live_artifact':
case 'live_artifact_refresh':
case 'plugin_candidate':
return true;
case 'tool_result':
return false;
case 'raw':
return false;
case 'status':
return !HIDDEN_BRAND_ASSISTANT_STATUS_LABELS.has(event.label);
case 'usage':
case 'diagnostic':
case 'conversation_title':
return false;
}
}
export function ChatPane({
messages,
streaming,
loading = false,
sendDisabled = false,
queuedItems = [],
error,
projectId,
sessionMode = 'design',
onSessionModeChange,
projectKindForTracking = null,
projectFiles,
activeProjectFileName = null,
hasActiveDesignSystem = false,
activeDesignSystem = null,
projectFileNames,
projectResolvedDir,
onEnsureProject,
previewComments = [],
attachedComments = [],
onAttachComment,
onDetachComment,
onDeleteComment,
onSend,
onRetry,
onResumeRun,
onStop,
onRemoveQueuedSend,
onUpdateQueuedSend,
onReorderQueuedSends,
onSendQueuedNow,
onRequestOpenFile,
onRequestPluginDetails,
onRequestDesignSystemDetails,
onRequestPluginFolderAgentAction,
activePluginActionPaths,
hiddenPluginActionPaths,
onShareToOpenDesign,
shareToOpenDesignBusyMessageId,
forceStreamingMessageIds,
liveToolInput,
initialDraft,
onboardingStarterPath = null,
composerPlaceholder,
onSubmitQuestionForm,
questionFormSubmitDisabled = false,
onContinueRemainingTasks,
onAssistantFeedback,
onBrandBrowserAssistConfirm,
onArtifactShare,
onArtifactDownload,
onForkFromMessage,
forkingMessageId = null,
onNewConversation,
newConversationDisabled = false,
conversations,
activeConversationId,
messagesConversationId = null,
onSelectConversation,
onDeleteConversation,
onOpenSettings,
showByokRecoveryAction = false,
onSwitchToLocalCli,
onOpenAmrSettings,
onSwitchToAmrAndRetry,
onLaunchAntigravityOauth,
onOpenMcpSettings,
onBrowsePlugins,
onOpenConnectors,
connectRepoNeeded,
githubConnected,
onConnectRepo,
brandExtractionComplete = false,
brandEnrichmentEligible,
onContinueBrandEnrichment,
brandEnrichmentBusy,
onContinueBrandAgentExtraction,
continueBrandAgentExtractionBusy,
onContinueBrandExtraction,
continueBrandExtractionBusy,
onCreateDesignFromActiveDesignSystem,
createDesignFromActiveDesignSystemBusy,
onCreateDesignSystemFromProject,
createDesignSystemFromProjectBusy,
composerDraftSignal,
petConfig,
onAdoptPet,
onTogglePet,
onOpenPetSettings,
projectMetadata,
onProjectMetadataChange,
activeWorkspaceContext,
initialWorkspaceContexts = [],
workspaceContexts = [],
currentSkillId = null,
onProjectSkillChange,
researchAvailable,
activePluginSnapshot,
skills = [],
byokApiProtocol,
byokImageModel,
onChangeByokImageModel,
byokVideoModel,
onChangeByokVideoModel,
byokSpeechModel,
onChangeByokSpeechModel,
byokSpeechVoice,
onChangeByokSpeechVoice,
composerLeadingAccessory,
composerFooterAccessory,
currentDesignSystemId,
onActiveDesignSystemChange,
onShowToast,
chatLogTray,
onBack,
backLabel,
projectHeader,
designSystemPicker,
config,
}: Props) {
const t = useT();
const analytics = useAnalytics();
const displayMessages = useMemo(
() => messages.filter((message) => !shouldHideEmptyBrandAssistantMessage(message, projectMetadata)),
[messages, projectMetadata],
);
const amrProfile = config?.agentCliEnv?.amr?.[AMR_PROFILE_ENV_KEY] ?? null;
const [inlineAmrLoginStatus, setInlineAmrLoginStatus] =
useState<VelaLoginStatus | null>(null);
const logRef = useRef<HTMLDivElement | null>(null);
// Guards the inline AMR sign-in card so a successful login auto-retries the
// failed run exactly once (the pill's onStatusChange fires loggedIn on every
// poll). Keyed by the failed assistant's id.
const amrAuthRetriedRef = useRef<string | null>(null);
// Tracks the last observed AMR login state so we retry only on a real
// signed-out -> signed-in transition. Without this, a run that keeps failing
// AMR_AUTH_REQUIRED while /status already reports signed-in would auto-retry
// forever (each retry is a new assistant id, so the id guard alone never
// converges).
const amrAuthPrevLoggedInRef = useRef<boolean | undefined>(undefined);
const chatLogScrollIdleTimerRef = useRef<number | null>(null);
const historyWrapRef = useRef<HTMLDivElement | null>(null);
const composerRef = useRef<ChatComposerHandle | null>(null);
const composerSlotRef = useRef<HTMLDivElement | null>(null);
const composerLayerRef = useRef<HTMLDivElement | null>(null);
const pinnedTodoRef = useRef<HTMLDivElement | null>(null);
const queuedSendStripRef = useRef<HTMLDivElement | null>(null);
const didInitialScrollRef = useRef(false);
const runFailedToastSurfaceKeysRef = useRef<Set<string>>(new Set());
// Tracks whether the user is glued close enough to the bottom that
// streamed content should auto-follow. Distinct from the jump-button
// state below, which uses a wider threshold (120px) so the affordance
// stays visible for short scroll-ups. Auto-follow needs the tighter
// 80px cutoff: scrolling ~90px up is an intentional pause that
// shouldn't be yanked back the moment the next chunk streams in.
const pinnedToBottomRef = useRef(true);
const scrolledToFormRef = useRef<Set<string>>(new Set());
const refreshInlineAmrLoginStatus = useCallback(async (options: { refresh?: boolean } = {}) => {
const next = await fetchVelaLoginStatus(options).catch(() => null);
if (next) setInlineAmrLoginStatus(next);
return next;
}, []);
useEffect(() => {
void refreshInlineAmrLoginStatus();
const onAmrLoginStatusChange = (event: Event) => {
const reason = amrLoginStatusEventReason(event);
if (reason === 'login-canceled') return;
void refreshInlineAmrLoginStatus();
};
window.addEventListener(AMR_LOGIN_STATUS_EVENT, onAmrLoginStatusChange);
return () => {
window.removeEventListener(AMR_LOGIN_STATUS_EVENT, onAmrLoginStatusChange);
};
}, [refreshInlineAmrLoginStatus]);
useEffect(() => {
const refreshAfterExternalAmrReturn = () => {
if (document.visibilityState === 'hidden') return;
void refreshInlineAmrLoginStatus({ refresh: true });
};
window.addEventListener('focus', refreshAfterExternalAmrReturn);
document.addEventListener('visibilitychange', refreshAfterExternalAmrReturn);
return () => {
window.removeEventListener('focus', refreshAfterExternalAmrReturn);
document.removeEventListener('visibilitychange', refreshAfterExternalAmrReturn);
};
}, [refreshInlineAmrLoginStatus]);
// "Anchor the just-sent turn to the top" (ChatGPT-style). On send we pin
// the user's message to the top of the viewport and let the reply stream
// below it instead of following the bottom. `pending` is armed by the
// composer's onSend; the messages effect promotes it to `active` once the
// new user turn actually renders. A dynamic tail spacer reserves just
// enough real, scrollable blank space below the turn so the message can
// reach the top even when the reply is short. The spacer is only resized
// while the message sits at its pinned position — once the user scrolls
// below it, the reserved blank stays put (no collapse, no jump).
const anchorPendingRef = useRef(false);
const anchorActiveRef = useRef(false);
const tailSpacerRef = useRef<HTMLDivElement | null>(null);
const prevStreamingRef = useRef(streaming);
const prevLastUserIdRef = useRef<string | undefined>(undefined);
// AssistantMessage's interaction callbacks are re-created per render and
// excluded from its memo comparison (so streaming doesn't re-render every
// message). Route them through this ref so a memoized message still calls the
// LATEST handler. See areAssistantMessagePropsEqual in AssistantMessage.tsx.