-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathChatComposer.tsx
More file actions
5939 lines (5743 loc) · 223 KB
/
Copy pathChatComposer.tsx
File metadata and controls
5939 lines (5743 loc) · 223 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
'use client';
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { createPortal } from 'react-dom';
import { Button } from '@open-design/components';
import { useI18n } from '../i18n';
import { localizePluginDescription, localizePluginTitle } from './plugins-home/localization';
import type { Dict, Locale } from '../i18n/types';
import {
localizeSkillDescription,
localizeSkillName,
} from '../i18n/content';
import { useAnalytics } from '../analytics/provider';
import {
trackChatPanelClick,
trackComposerBarClick,
trackComposerSessionModeClick,
trackContextLinkResult,
trackDesignToolboxClick,
trackFigmaHelpModalSurfaceView,
trackFileUploadResult,
trackProjectReferenceModalSurfaceView,
} from '../analytics/events';
import type {
ComposerBarClickProps,
DesignToolboxClickProps,
} from '@open-design/contracts/analytics';
import { sessionModeToTracking } from '@open-design/contracts/analytics';
import { deriveUploadCohort } from '../analytics/upload-tracking';
import { projectRawUrl, uploadProjectFiles, openFolderDialog, fetchRecentLinkedDirs, pushRecentLinkedDir, dirExists, applyLibraryAsset, fetchLibraryAssetElementHtml } from "../providers/registry";
import {
duplicatePluginAsProject,
patchProject,
resolvedWorkspaceContextForWrite,
} from "../state/projects";
import { navigate } from '../router';
import { fetchMcpServers } from "../state/mcp";
import type { McpServerConfig, McpTemplate } from "../state/mcp";
import { listPlugins } from "../state/projects";
import type { AppConfig, ChatAttachment, ChatCommentAttachment, Project, ProjectFile, ProjectMetadata, SkillSummary } from "../types";
import type {
ContextItem,
AppliedPluginSnapshot,
ChatAnalyticsEntryFrom,
ChatSessionMode,
ConnectorDetail,
InstalledPluginRecord,
PluginSourceKind,
ResearchOptions,
RunContextSelection,
WorkspaceContextItem,
} from '@open-design/contracts';
import { buildVisualAnnotationAttachment, commentTargetDisplayName } from '../comments';
import { Icon, type IconName } from "./Icon";
import { ComposerPlusMenu, PLUS_SUBMENU_RESOURCE_KIND, type PlusMenuSubmenu } from './ComposerPlusMenu';
import { LibraryPicker } from './LibraryPicker';
import { FigmaImportModal } from './FigmaImportModal';
import { FigmaHelpModal } from './FigmaHelpModal';
import {
ProjectReferenceModal,
type ProjectReferenceSelection,
} from './ProjectReferenceModal';
import { assetTitle, elementMetaOf } from './LibraryAssetMeta';
import { ComposerModePicker } from './ComposerModePicker';
import type { LibraryAsset, LibraryElementMeta } from '@open-design/contracts';
import {
DESIGN_TOOLBOX_ACTIONS,
designToolboxActionBadge,
designToolboxActionDescription,
designToolboxActionMatchesQuery,
designToolboxActionTitle,
findDesignToolboxSkill,
getDesignToolboxAction,
skillMatchesQuery,
type DesignToolboxAction,
type DesignToolboxActionId,
} from '../runtime/design-toolbox';
import { ComposerPluginPreview } from './ComposerPluginPreview';
import { computeToolboxDetailPosition } from './composer-detail-position';
import { PluginDetailsModal } from "./PluginDetailsModal";
import { SkillDetailsModal } from './SkillDetailsModal';
import { PluginsSection, type PluginsSectionHandle } from "./PluginsSection";
import { BUILT_IN_PETS, CUSTOM_PET_ID } from "./pet/pets";
import {
inlineMentionToken,
mentionTokenPresent,
type InlineMentionEntity,
} from '../utils/inlineMentions';
import { workspaceContextLinkedDir, workspaceContextLinkedDirs } from './workspace-context';
import { useWorkspaceContext } from '../collab/useWorkspaceContext';
import {
LexicalComposerInput,
type LexicalComposerInputHandle,
type CaretRect,
} from './composer/LexicalComposerInput';
import { CaretFloatingLayer } from './composer/CaretFloatingLayer';
import { ANNOTATION_EVENT, type AnnotationEventDetail } from "./PreviewDrawOverlay";
/**
* Window event for staging attachments that are ALREADY uploaded to the
* project (ChatAttachment shape, not File). Mirrors ANNOTATION_EVENT's
* pattern; used by surfaces that materialize files themselves — e.g. the
* design browser's hover "添加到对话" capture, which writes the PNG via
* writeProjectBase64File before notifying the composer.
*/
export const STAGE_ATTACHMENT_EVENT = 'opendesign:stage-attachment';
export interface StageAttachmentEventDetail {
attachments: ChatAttachment[];
}
import { DesignSystemSwitchPicker } from "./DesignSystemSwitchPicker";
import { listenForConnectorsChanged } from './connectors-events';
import { fetchConnectorCatalogSnapshot } from './connectors-state';
import { PlaceholderCarousel } from './home-hero/PlaceholderCarousel';
import type { PlaceholderScenario } from './home-hero/placeholderScenarios';
type TranslateFn = (key: keyof Dict, vars?: Record<string, string | number>) => string;
interface TrackedWorkspaceLinkedDir {
dir: string;
previousLinkedDirs: string[];
}
function dedupeWorkspaceContextItems(items: WorkspaceContextItem[]): WorkspaceContextItem[] {
const out: WorkspaceContextItem[] = [];
const seen = new Set<string>();
for (const item of items) {
const key = `${item.kind}:${item.id}`;
if (seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
}
function trackedWorkspaceLinkedDirsForContexts(
items: WorkspaceContextItem[],
linkedDirs: string[],
): Record<string, TrackedWorkspaceLinkedDir> {
const out: Record<string, TrackedWorkspaceLinkedDir> = {};
for (const item of items) {
const dir = workspaceContextLinkedDir(item) ?? '';
if (!dir || !linkedDirs.includes(dir)) continue;
out[item.id] = {
dir,
previousLinkedDirs: linkedDirs.filter((linkedDir) => linkedDir !== dir),
};
}
return out;
}
type ToolsTab = 'plugins' | 'skills' | 'mcp' | 'import';
type MentionTab = 'all' | 'tabs' | 'files' | 'plugins' | 'skills' | 'mcp' | 'connectors';
const USER_PLUGIN_SOURCE_KINDS = new Set<PluginSourceKind>([
'user',
'project',
'marketplace',
'github',
'url',
'local',
]);
interface SlashCommand {
id: string;
// Visible label, e.g. `/hatch`. Shown in the popover row.
label: string;
// Text inserted into the draft when the user picks the entry. The
// cursor is positioned at the end of `insert`, so a trailing space
// is the difference between a "ready for argument" command and a
// "submit immediately" one.
insert: string;
// i18n key of the short description shown next to the label.
descKey: keyof Dict;
// Optional argument hint shown after the description.
argHint?: string;
// Icon glyph from the project Icon set.
icon: 'sparkles' | 'eye' | 'sliders';
}
type DesignToolboxResourceKind =
| 'skill'
| 'plugin'
| 'mcp'
| 'mcp-template'
| 'connector'
| 'file';
interface DesignToolboxResourceIndex {
skills: SkillSummary[];
plugins: InstalledPluginRecord[];
mcpServers: McpServerConfig[];
mcpTemplates: McpTemplate[];
connectors: ConnectorDetail[];
projectFiles: ProjectFile[];
}
type DesignToolboxResourceBase = {
key: string;
kind: DesignToolboxResourceKind;
id: string;
title: string;
subtitle: string;
badge: string;
icon: IconName;
searchText: string;
};
type DesignToolboxResource =
| (DesignToolboxResourceBase & { kind: 'skill'; skill: SkillSummary })
| (DesignToolboxResourceBase & { kind: 'plugin'; plugin: InstalledPluginRecord })
| (DesignToolboxResourceBase & { kind: 'mcp'; server: McpServerConfig })
| (DesignToolboxResourceBase & { kind: 'mcp-template'; template: McpTemplate })
| (DesignToolboxResourceBase & { kind: 'connector'; connector: ConnectorDetail })
| (DesignToolboxResourceBase & { kind: 'file'; file: ProjectFile });
export type ChatSendOutcome = void | 'restore-draft';
interface Props {
projectId: string | null;
projectFiles: ProjectFile[];
activeProjectFileName?: string | null;
streaming: boolean;
sessionMode?: ChatSessionMode;
onSessionModeChange?: (mode: ChatSessionMode) => void;
sendDisabled?: boolean;
// Read-only viewer of a team-shared project: makes the Lexical editor
// non-editable (in addition to `sendDisabled` blocking the send action) so
// the user cannot type into the composer at all.
inputDisabled?: boolean;
initialDraft?: string;
composerPlaceholder?: string;
placeholderScenarios?: ReadonlyArray<PlaceholderScenario>;
draftStorageKey?: string;
// Lazy ensure — the composer calls this before its first upload, so the
// project folder exists on disk before files land in it. Returns the
// project id when ready.
onEnsureProject: () => Promise<string | null>;
commentAttachments?: ChatCommentAttachment[];
onRemoveCommentAttachment?: (id: string) => void;
// Available skills the user can compose into a turn via @<skill>. The
// chat layer already filters out disabled skills before passing them in
// here, so the picker can render the list as-is. Keep this optional so
// the composer still works on surfaces that don't show a skills picker
// (e.g. tests, screenshot harnesses).
skills?: SkillSummary[];
onSend: (
prompt: string,
attachments: ChatAttachment[],
commentAttachments: ChatCommentAttachment[],
meta?: ChatSendMeta,
) => ChatSendOutcome | Promise<ChatSendOutcome>;
onStop: () => void;
// Opens the global settings dialog (CLI / model / agent picker). The
// composer's leading gear icon routes here so users can switch models
// without leaving the chat.
onOpenSettings?: () => void;
// Opens settings on the External MCP tab. Wired from ChatPane → App.
// The composer's `/mcp` slash command and the MCP picker button route here.
onOpenMcpSettings?: () => void;
// The "+" menu's "add plugin" / "add connector" rows route to the home
// surfaces (plugin registry / connector integrations). Wired from
// ChatPane → ProjectView → App. Omitted → the add rows are hidden.
onBrowsePlugins?: () => void;
onOpenConnectors?: () => void;
/** Reports which standalone quick-pill popover is open (null when none), so
* the host that renders the pills can carry `aria-expanded` on them. The
* popovers live here but their triggers do not. */
onStandalonePanelChange?: (panel: ComposerStandalonePanel) => void;
// Optional pet wiring. The composer no longer renders a visible pet
// entry, but existing manual `/pet` commands still route here.
petConfig?: AppConfig['pet'];
onAdoptPet?: (petId: string) => void;
onTogglePet?: () => void;
onOpenPetSettings?: () => void;
researchAvailable?: boolean;
projectMetadata?: ProjectMetadata;
// Fired after the daemon accepts a metadata PATCH, with the authoritative
// post-patch project (fresh `updatedAt` included). Callers must replace
// their whole project copy with it: forwarding only the metadata onto a
// stale copy lets an older detail snapshot win recency comparisons and
// shadow the change (e.g. the working-dir label never updating).
onProjectMetadataChange?: (updated: Project) => void;
activeWorkspaceContext?: WorkspaceContextItem | null;
initialWorkspaceContexts?: WorkspaceContextItem[];
workspaceContexts?: WorkspaceContextItem[];
// BYOK image-model picker shown above the textarea for protocols that
// inject the daemon-side generate_image tool (SenseAudio, AIHubMix).
// Hidden for every other BYOK tab so the composer stays clean. The
// state owner is ProjectView (per-session, reset on refresh);
// ChatComposer is a fully controlled select.
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;
currentSkillId?: string | null;
onProjectSkillChange?: (skillId: string | null) => void;
// Set when the project was created with a plugin already pinned
// (PluginLoopHome on Home). When provided, the in-composer plugin
// rail collapses to the single pinned plugin so the user can see
// which plugin is active without being offered every other installed
// plugin (the user reported "选了 new-generation, 结果 composer 显
// 示了多个 plugin"). The active plugin still appears as an
// ActivePluginChip on each user message (see UserMessage in
// ChatPane). Pass `null` (or omit) to render the full rail.
pinnedPluginId?: string | null;
footerAccessory?: ReactNode;
// Slot rendered in the composer's bottom toolbar, immediately right of the
// "+" menu. Hosts the working-directory pill so the folder selector sits by
// the composer (mirroring the home input) instead of the file-panel header.
leadingAccessory?: ReactNode;
// Design-system picker slot rendered at the top of the composer (above
// the textarea). The former standalone chrome header row was removed;
// ProjectView owns the project record so it renders the picker as a slot.
designSystemPicker?: ReactNode;
// Project's current `designSystemId`. The mid-chat design-system picker
// uses this to surface a "current" indicator and to no-op a redundant
// switch. Optional so test/screenshot harnesses can omit it.
currentDesignSystemId?: string | null;
// Fires after a successful `PATCH /api/projects/:id` from the mid-chat
// design-system picker. Receives the full patched `Project` straight
// from the PATCH response so the parent replaces its mirror wholesale —
// rebuilding from a stale `project` prop would drop server-owned fields
// the daemon refreshes on every PATCH (e.g. `updatedAt`).
onActiveDesignSystemChange?: (project: Project) => void;
// Optional transient banner sink. The composer emits one short message
// here when a mid-chat design-system switch lands (or fails) so the user
// has explicit confirmation without re-opening the picker.
onShowToast?: (message: string) => void;
}
// Imperative handle so ancestors (e.g. example chips in ChatPane) can
// push text into the composer without owning its draft state.
export interface ChatComposerDraftOptions {
entryFrom?: ChatAnalyticsEntryFrom;
sessionMode?: ChatSessionMode;
}
/** Which of the two standalone quick-pill popovers is open, if either. */
export type ComposerStandalonePanel = 'plugins' | 'toolbox' | null;
export interface ChatComposerHandle {
setDraft: (text: string, options?: ChatComposerDraftOptions) => void;
restoreDraft: (draft: {
text: string;
attachments?: ChatAttachment[];
commentAttachments?: ChatCommentAttachment[];
/**
* The queued turn's meta. When present, restoreDraft rebuilds the staged
* plugin / connector / skill / MCP context (and re-shows their chips) so
* editing a queued item keeps its bindings instead of silently dropping
* them.
*/
meta?: ChatSendMeta;
}) => void;
focus: () => void;
/**
* Run a design-toolbox action by id from outside the composer (e.g. the
* assistant "next step" card). Resolves the action, matches its preferred
* skill, and seeds the composer draft with the action prompt + `@skill`
* mention — identical to picking the action inside the toolbox panel, so the
* draft still waits for the user to send. No-op for an unknown id.
*/
applyDesignToolboxAction: (id: DesignToolboxActionId) => void;
/**
* Seed the composer with a specific skill by id (same path as picking it in
* the toolbox panel). Used by the next-step card's full skill list. No-op for
* an unknown id.
*/
applyDesignToolboxSkill: (skillId: string) => void;
/** Open the standalone toolbox popover (the 设计百宝箱 quick pill above the
* composer input; the "+" menu no longer carries a toolbox row). `opener` is
* the control focus returns to when the popover is dismissed. */
openDesignToolbox: (opener?: HTMLElement | null) => void;
/** Open the standalone plugins popover (the 插件 quick pill above the
* composer input; the "+" menu no longer carries a plugins row). `opener` is
* the control focus returns to when the popover is dismissed. */
openPluginsPanel: (opener?: HTMLElement | null) => void;
/** Schedule closing whichever standalone popover is open (hover-leave from
* a quick pill); re-opening or hovering the popup cancels it. */
scheduleComposerPanelClose: () => void;
/**
* Open the composer "+" menu from outside, optionally landing on a specific
* flyout.
*/
openPlusMenu: (submenu?: PlusMenuSubmenu) => void;
}
export interface ChatSendMeta {
queueOnly?: boolean;
research?: ResearchOptions;
context?: RunContextSelection;
appliedPluginSnapshot?: AppliedPluginSnapshot;
appliedPluginSnapshotId?: string;
inlineAppliedPlugin?: {
pluginId: string;
label: string;
};
// Per-turn skill ids picked via the @-mention popover. The chat layer
// forwards these to the daemon's `skillIds` field so the system prompt
// for this run only is composed with the extra skill bodies, without
// touching the project's persistent `skillId`.
skillIds?: string[];
/** Overrides the run_created / run_finished `entry_from` analytics prop for
* this send (e.g. 'mark' when the turn is sent from the Mark draw overlay).
* Behavior never depends on it; it only shapes PostHog props. */
entryFrom?: ChatAnalyticsEntryFrom;
/** One-shot run mode override for seeded follow-ups before parent state catches up. */
sessionMode?: ChatSessionMode;
}
/**
* The chat composer: textarea + paste/drop/attach buttons + @-mention
* picker. Attachments are uploaded into the active project's folder so
* the agent can reference them by relative path on its next turn.
*
* `@` typed at a word boundary opens a popover listing project files.
* Selecting one inserts `@<path>` into the prompt and stages it as an
* attachment so the daemon also includes it explicitly.
*/
export const ChatComposer = forwardRef<ChatComposerHandle, Props>(
function ChatComposer(
{
projectId,
projectFiles,
activeProjectFileName = null,
streaming,
sessionMode = 'design',
onSessionModeChange,
sendDisabled = false,
inputDisabled = false,
initialDraft,
composerPlaceholder,
placeholderScenarios = [],
draftStorageKey,
onEnsureProject,
commentAttachments = [],
onRemoveCommentAttachment,
skills = [],
onSend,
onStop,
onOpenMcpSettings,
onBrowsePlugins,
onStandalonePanelChange,
onOpenConnectors,
petConfig,
onAdoptPet,
onTogglePet,
onOpenPetSettings,
researchAvailable = false,
projectMetadata,
onProjectMetadataChange,
activeWorkspaceContext = null,
initialWorkspaceContexts = [],
workspaceContexts = [],
byokApiProtocol,
byokImageModel,
onChangeByokImageModel,
byokVideoModel,
onChangeByokVideoModel,
byokSpeechModel,
onChangeByokSpeechModel,
byokSpeechVoice,
onChangeByokSpeechVoice,
currentSkillId = null,
onProjectSkillChange,
pinnedPluginId = null,
footerAccessory,
leadingAccessory,
designSystemPicker,
onShowToast,
},
ref
) {
const { locale, t } = useI18n();
const analytics = useAnalytics();
const workspaceContextState = useWorkspaceContext();
const { context: workspaceContext } = workspaceContextState;
const activeFileContext =
projectMetadata?.importedFrom === 'folder' && activeProjectFileName
? activeProjectFileName
: null;
const activeFileDisplayName = activeFileContext ? lastPathSegment(activeFileContext) : null;
const [draft, setDraft] = useState(() => initialDraft ?? loadComposerDraft(draftStorageKey) ?? "");
const [placeholderScenario, setPlaceholderScenario] = useState<PlaceholderScenario | null>(null);
const composerRootRef = useRef<HTMLDivElement | null>(null);
const pendingSessionModeRef = useRef<ChatSessionMode | null>(null);
// Synchronous mirror of `draft`. Event handlers that mutate the draft off
// a captured render closure (notably the annotation listener, where two
// uploads can resolve concurrently) read/write this ref so their edits
// compose instead of clobbering one another. Kept in lockstep with `draft`
// by handleEditorChange (the editor is the single source for typing) and by
// the programmatic-set paths below.
const draftRef = useRef(draft);
const previousSessionModeRef = useRef(sessionMode);
useEffect(() => {
if (previousSessionModeRef.current === sessionMode) return;
if (pendingSessionModeRef.current && pendingSessionModeRef.current !== sessionMode) {
pendingSessionModeRef.current = null;
}
previousSessionModeRef.current = sessionMode;
}, [sessionMode]);
// chat_panel page_view fires from ProjectView (which outlives
// conversation switches) so the event measures real chat-panel
// entries rather than ChatComposer remounts. See PR #2285 review
// 2026-05-20 04:08 for the rationale.
const [staged, setStaged] = useState<ChatAttachment[]>([]);
// Manual editor height set by dragging the shell's gray backdrop up/down.
// null = the default auto-grow min/max behavior.
const [manualEditorHeight, setManualEditorHeight] = useState<number | null>(null);
const nextAttachmentOrderRef = useRef(0);
const [libraryPickerOpen, setLibraryPickerOpen] = useState(false);
const [figmaModalOpen, setFigmaModalOpen] = useState(false);
const [figmaHelpOpen, setFigmaHelpOpen] = useState(false);
const [projectReferenceOpen, setProjectReferenceOpen] = useState(false);
const [stagedVisualComments, setStagedVisualComments] = useState<ChatCommentAttachment[]>([]);
const streamingAnnotationSendPendingRef = useRef(false);
// Remembers the entry_from that the deferred streaming send must carry once
// it flushes. The Mark draw-overlay tags 'mark' synchronously; without this
// the flush effect would report the run as the default composer entry.
const streamingAnnotationSendEntryFromRef = useRef<ChatSendMeta['entryFrom']>(undefined);
const [streamingAnnotationSendPending, setStreamingAnnotationSendPendingState] = useState(false);
// Skills the user has @-mentioned for this turn. We dedupe on id and
// strip the chip when the user removes the corresponding `@<skill>`
// token from the draft, keeping draft and chips in sync.
const [stagedSkills, setStagedSkills] = useState<SkillSummary[]>([]);
// Legacy standalone design-toolbox popover. The next-step card now renders
// its own cascading skill menu, so nothing opens this anymore; kept compiling
// behind `openDesignToolbox` until the panel subsystem is removed wholesale.
const [designToolboxOpen, setDesignToolboxOpen] = useState(false);
const [pluginsPanelOpen, setPluginsPanelOpen] = useState(false);
// Shared close timer for the two hover-opened standalone popovers (插件 /
// 设计百宝箱). Leaving a quick pill schedules a close; re-entering the pill
// or the popup cancels it, so the pointer can travel pill → popup freely.
const panelCloseTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
function cancelComposerPanelClose() {
if (panelCloseTimerRef.current) {
clearTimeout(panelCloseTimerRef.current);
panelCloseTimerRef.current = null;
}
}
function scheduleComposerPanelClose() {
cancelComposerPanelClose();
panelCloseTimerRef.current = setTimeout(() => {
panelCloseTimerRef.current = null;
setPluginsPanelOpen(false);
setDesignToolboxOpen(false);
}, 260);
}
useEffect(() => () => {
if (panelCloseTimerRef.current) clearTimeout(panelCloseTimerRef.current);
}, []);
// The quick pill a standalone popover was opened from. Both popovers move
// focus inside themselves (the plugins pane autofocuses its search box), so
// a dismissal has to hand focus back — the pill lives in the host above the
// composer and is the only control still mounted afterwards.
const panelOpenerRef = useRef<HTMLElement | null>(null);
/** Close whichever standalone popover is open BECAUSE THE USER DISMISSED IT
* (Escape, backdrop) and return focus to the pill that opened it. Paths
* where the user picked something keep the plain setters: the composer
* takes focus there, and pulling it back to the pill would fight that. */
function dismissStandalonePanels() {
cancelComposerPanelClose();
setPluginsPanelOpen(false);
setDesignToolboxOpen(false);
const opener = panelOpenerRef.current;
panelOpenerRef.current = null;
opener?.focus();
}
const openStandalonePanel: ComposerStandalonePanel = designToolboxOpen
? 'toolbox'
: pluginsPanelOpen
? 'plugins'
: null;
useEffect(() => {
onStandalonePanelChange?.(openStandalonePanel);
}, [onStandalonePanelChange, openStandalonePanel]);
// Escape closes the popover, matching ComposerPlusMenu's own document-level
// handler. Without it, Escape pressed while focus sat in the plugin search
// did nothing at all.
useEffect(() => {
if (openStandalonePanel == null) return;
function onKey(event: KeyboardEvent) {
if (event.key !== 'Escape') return;
dismissStandalonePanels();
}
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [openStandalonePanel]);
// External "+"-menu open request (next-step quick pills) — nonce-keyed so
// every pill click re-opens even after the menu was dismissed.
const [plusMenuOpenRequest, setPlusMenuOpenRequest] = useState<
{ nonce: number; submenu?: PlusMenuSubmenu } | null
>(null);
const [stagedMcpServers, setStagedMcpServers] = useState<McpServerConfig[]>([]);
const [stagedConnectors, setStagedConnectors] = useState<ConnectorDetail[]>([]);
const linkedDirs = projectMetadata?.linkedDirs ?? [];
const [stagedWorkspaceContexts, setStagedWorkspaceContexts] = useState<WorkspaceContextItem[]>(
() => dedupeWorkspaceContextItems(initialWorkspaceContexts),
);
const [workspaceLinkedDirAdds, setWorkspaceLinkedDirAdds] = useState<Record<string, TrackedWorkspaceLinkedDir>>(
() => trackedWorkspaceLinkedDirsForContexts(initialWorkspaceContexts, linkedDirs),
);
const [promotedWorkspaceContextDir, setPromotedWorkspaceContextDir] = useState<string | null>(null);
const [dismissedWorkspaceContextId, setDismissedWorkspaceContextId] = useState<string | null>(null);
const activeWorkspaceContextId = activeWorkspaceContext?.id ?? null;
const previousWorkspaceContextIdRef = useRef<string | null>(activeWorkspaceContextId);
const [dragActive, setDragActive] = useState(false);
// Lexical owns the caret, so the mention/slash trigger state only carries
// the typed query — no cursor offset.
const [mention, setMention] = useState<{ q: string } | null>(null);
// Active-row index for the @-popover's visible union (files → tabs →
// plugins → skills → mcp → connectors). Resets to 0 whenever the query
// identity or tab changes; drives the visual highlight + Enter/Tab target.
const [mentionIndex, setMentionIndex] = useState(0);
const [mentionTab, setMentionTab] = useState<MentionTab>('all');
// Viewport caret box the floating popover anchors against. Sampled by the
// editor at trigger-detection time; null when no trigger is live.
const [caretRect, setCaretRect] = useState<CaretRect | null>(null);
// Slash-command popover state — when the draft starts with `/` and the
// cursor is still inside that token (no space committed yet), we show a
// small palette of supported commands. The query is the text after `/`
// so the user can type-to-filter.
const [slash, setSlash] = useState<{ q: string } | null>(null);
const [slashIndex, setSlashIndex] = useState(0);
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
// External MCP servers configured by the user. Fetched lazily on mount;
// shown in the slash-command palette so `/mcp <id>` inserts a hint into
// the prompt that nudges the model to use that server's tools.
const [mcpServers, setMcpServers] = useState<McpServerConfig[]>([]);
const [mcpTemplates, setMcpTemplates] = useState<McpTemplate[]>([]);
const [connectors, setConnectors] = useState<ConnectorDetail[]>([]);
// Installed plugins, fetched lazily for the tools-menu Plugins tab and
// the @-mention picker. Both surfaces share the same list so applying
// a plugin from either path lands on the same project context.
const [installedPlugins, setInstalledPlugins] = useState<InstalledPluginRecord[]>([]);
// Detail modal — opened from a context chip click (kind === 'plugin')
// or from the tools-menu "Details" affordance.
const [detailsRecord, setDetailsRecord] = useState<InstalledPluginRecord | null>(null);
const [detailsSkill, setDetailsSkill] = useState<{
id: string;
summary?: SkillSummary | null;
} | null>(null);
const [activeAppliedPlugin, setActiveAppliedPlugin] =
useState<AppliedPluginSnapshot | null>(null);
const pluginsSectionRef = useRef<PluginsSectionHandle | null>(null);
const inlineBackedPluginRef = useRef<{ id: string; label: string } | null>(null);
async function duplicateDetailsPlugin(record: InstalledPluginRecord) {
try {
const result = await duplicatePluginAsProject(record.id, {
name: localizePluginTitle(locale, record),
}, resolvedWorkspaceContextForWrite(workspaceContextState));
setDetailsRecord(null);
navigate({
kind: 'project',
projectId: result.projectId,
conversationId: result.conversationId,
fileName: result.relPath,
});
} catch {
onShowToast?.(t('pluginCard.duplicateFailed'));
}
}
// Consolidated "tools" popover — a single dropdown anchored to the
// leading sliders icon that hosts project context, MCP, Import actions,
// and a shortcut to open the full Settings dialog. Replaces the previous
// row of three standalone buttons (which overflowed in narrow chats).
// The "+" menu (ComposerPlusMenu) owns its own open / submenu state.
// Defer the (large) plugin / MCP / connector fetches until the composer is
// actually used — first focus, the tools popover opening, an @/slash
// trigger, or a pre-seeded draft. An untouched empty composer (e.g. a home
// surface the user bounces off, or a background chat) never pays for the
// full plugin-manifest list. Latches once true and never resets.
const [composerEngaged, setComposerEngaged] = useState(
() => (draft ?? '').trim().length > 0,
);
const fileInputRef = useRef<HTMLInputElement | null>(null);
// The Lexical editor handle — drives text/mention/clear/focus from the
// host. Replaces the old textareaRef + manual selection plumbing. IME
// composition guarding now lives inside the editor's command handlers.
const editorRef = useRef<LexicalComposerInputHandle | null>(null);
// Always points at the latest `applyDesignToolboxAction` closure so the
// imperative handle (whose deps array doesn't track `draft`/`t`) never seeds
// the composer from a stale draft when the next-step card fires an action.
const applyDesignToolboxActionRef = useRef<(action: DesignToolboxAction) => void>(() => {});
// Same latest-closure trick for picking a skill by id from the next-step card.
const applyDesignToolboxSkillByIdRef = useRef<(skillId: string) => void>(() => {});
// Best-effort entry_from carried from a guided Next-step action: the card
// only seeds the composer, so the tag is stashed here and consumed by the
// next `sendComposedTurn` (then cleared). An explicit meta.entryFrom always
// wins over this pending value.
const pendingEntryFromRef = useRef<ChatAnalyticsEntryFrom | null>(null);
const petEnabled = Boolean(onAdoptPet && onTogglePet);
const [recentDirs, setRecentDirs] = useState<string[]>([]);
useEffect(() => {
let cancelled = false;
void fetchRecentLinkedDirs().then((dirs) => {
if (!cancelled) setRecentDirs(dirs);
});
return () => {
cancelled = true;
};
}, []);
const rememberRecentDir = useCallback(async (dir: string) => {
setRecentDirs((prev) => [dir, ...prev.filter((d) => d !== dir)].slice(0, 5));
const persisted = await pushRecentLinkedDir(dir);
setRecentDirs(persisted);
}, []);
const visibleWorkspaceContext =
activeWorkspaceContext && activeWorkspaceContext.id !== dismissedWorkspaceContextId
? activeWorkspaceContext
: null;
const selectedWorkspaceContexts = useMemo(() => {
const out: WorkspaceContextItem[] = [];
const seen = new Set<string>();
const push = (item: WorkspaceContextItem | null | undefined) => {
if (!item) return;
const key = `${item.kind}:${item.id}`;
if (seen.has(key)) return;
seen.add(key);
out.push(item);
};
push(visibleWorkspaceContext);
for (const item of stagedWorkspaceContexts) push(item);
return out;
}, [stagedWorkspaceContexts, visibleWorkspaceContext]);
const selectedWorkspaceContextDirs = useMemo<string[]>(
() => workspaceContextLinkedDirs(selectedWorkspaceContexts),
[selectedWorkspaceContexts],
);
const workspaceContextMetadataLinkedDirList = useMemo<string[]>(
() =>
Array.from(new Set([
...Object.values(workspaceLinkedDirAdds).map((tracked) => tracked.dir),
...selectedWorkspaceContextDirs,
])),
[selectedWorkspaceContextDirs, workspaceLinkedDirAdds],
);
const workspaceContextLinkedDirList = useMemo<string[]>(
() =>
workspaceContextMetadataLinkedDirList.filter((dir) => dir !== promotedWorkspaceContextDir),
[promotedWorkspaceContextDir, workspaceContextMetadataLinkedDirList],
);
const workspaceContextLinkedDirSet = useMemo<Set<string>>(
() => new Set(workspaceContextLinkedDirList),
[workspaceContextLinkedDirList],
);
// The project's working directory: the local folder the agent can read
// (via `linkedDirs` → `--add-dir`). Shown in the WorkingDirPicker below
// the input, mirroring Home. Context-only folders are still linked for
// agent read access, but they should not become the displayed primary dir.
const workingDir = linkedDirs.find((dir) => !workspaceContextLinkedDirSet.has(dir)) ?? null;
// Live-check whether the selected working directory still exists, so a
// folder deleted from disk turns the picker red without a page reload.
// Re-checked when the dir changes, when the window/tab regains focus
// (e.g. after deleting it in Finder), and when the picker is opened.
const [workingDirMissing, setWorkingDirMissing] = useState(false);
const checkWorkingDir = useCallback(async () => {
if (!workingDir) {
setWorkingDirMissing(false);
return;
}
const ok = await dirExists(workingDir);
setWorkingDirMissing(!ok);
}, [workingDir]);
useEffect(() => {
void checkWorkingDir();
const onFocus = () => void checkWorkingDir();
const onVisible = () => {
if (document.visibilityState === 'visible') void checkWorkingDir();
};
window.addEventListener('focus', onFocus);
document.addEventListener('visibilitychange', onVisible);
return () => {
window.removeEventListener('focus', onFocus);
document.removeEventListener('visibilitychange', onVisible);
};
}, [checkWorkingDir]);
// initialDraft is only honored on the first non-empty value the parent
// hands us. After we seed once, the composer is fully under user control
// — re-renders that pass the same prompt back must not reseed. If the
// initial useState above already consumed a non-empty initialDraft we
// mark it seeded immediately, so an early clear by the user (typing or
// backspace before the parent stops passing initialDraft) does not get
// overwritten by the effect.
const seededRef = useRef(Boolean(initialDraft));
useEffect(() => {
if (seededRef.current) return;
if (initialDraft && initialDraft !== draft) {
setDraft(initialDraft);
seededRef.current = true;
} else if (initialDraft === undefined) {
seededRef.current = true;
}
}, [initialDraft, draft]);
useEffect(() => {
saveComposerDraft(draftStorageKey, draft);
}, [draftStorageKey, draft]);
useEffect(() => {
if (previousWorkspaceContextIdRef.current === activeWorkspaceContextId) return;
previousWorkspaceContextIdRef.current = activeWorkspaceContextId;
setDismissedWorkspaceContextId(null);
setPromotedWorkspaceContextDir(null);
}, [activeWorkspaceContextId]);
// Latch `composerEngaged` true on the first real interaction so the
// deferred fetches below run exactly once, when they are actually needed.
useEffect(() => {
if (composerEngaged) return;
if (draft.trim().length > 0 || mention || slash) {
setComposerEngaged(true);
}
}, [composerEngaged, draft, mention, slash]);
// Lazy-fetch the user's external MCP servers list (once engaged) so the
// `/mcp …` slash palette and the composer's MCP button popover have
// something to render. We deliberately do not reactively re-fetch when
// the user toggles servers from Settings — the dialog refreshes itself,
// and the chat composer rehydrates next time the user re-opens it. A
// background poll would be cheap but unnecessary for the typical
// edit-once-then-chat workflow.
useEffect(() => {
if (!composerEngaged) return;
let cancelled = false;
void (async () => {
const data = await fetchMcpServers();
if (cancelled || !data) return;
setMcpServers(data.servers);
setMcpTemplates(data.templates);
})();
return () => {
cancelled = true;
};
}, [composerEngaged]);
// Skills now come from the parent (App.tsx → ProjectView → ChatPane → ChatComposer)
// pre-filtered by enabled/disabled state. We no longer fetch a fresh list
// here to avoid showing skills the user has disabled via Settings.
// Lazy-fetch installed plugins once on mount; the tools-menu Plugins
// tab and the @-mention picker both consume this list.
useEffect(() => {
if (!projectId || !composerEngaged) return;
let cancelled = false;
void listPlugins().then((rows) => {
if (cancelled) return;
setInstalledPlugins(rows);
});
return () => {
cancelled = true;
};
}, [projectId, composerEngaged]);
useEffect(() => {
if (!composerEngaged) return;
let cancelled = false;
void fetchConnectorCatalogSnapshot().then((rows) => {
if (cancelled) return;
setConnectors(rows.filter((connector) => connector.status === 'connected'));
});
return () => {
cancelled = true;
};
}, [composerEngaged]);
useEffect(() => {
if (!composerEngaged) return;
let cancelled = false;
async function refreshConnectors() {
const rows = await fetchConnectorCatalogSnapshot({ refreshDiscovery: true });
if (cancelled) return;
setConnectors(rows.filter((connector) => connector.status === 'connected'));
}
const stopListening = listenForConnectorsChanged(() => void refreshConnectors());
return () => {
cancelled = true;
stopListening();
};
}, [composerEngaged]);
useEffect(() => {
const inlinePlugin = inlineBackedPluginRef.current;
if (!activeAppliedPlugin || inlinePlugin?.id !== activeAppliedPlugin.pluginId) return;
if (mentionTokenPresent(draft, inlinePlugin.label)) return;
inlineBackedPluginRef.current = null;
pluginsSectionRef.current?.clear();
}, [activeAppliedPlugin, draft]);
// Composer-side plugin list: hide bundled atoms (pipeline-only). Keep
// the full installed list available even when the project was created
// from a pinned plugin, so users can switch or layer different plugin
// context from the tools menu and @ picker.
const pluginsForComposer = useMemo<InstalledPluginRecord[]>(() => {
const allowedKinds = new Set(['skill', 'scenario', 'bundle']);
return installedPlugins.filter((p) => {
const k = p.manifest?.od?.kind;
return !k || allowedKinds.has(k);
});
}, [installedPlugins]);
const enabledMcpServers = useMemo(
() => mcpServers.filter((s) => s.enabled),
[mcpServers],
);
function inlineBackedPluginFromRestoredDraft(
text: string,
appliedPlugin: AppliedPluginSnapshot | null | undefined,
meta: ChatSendMeta | undefined,
): { id: string; label: string } | null {
if (!appliedPlugin) return null;
const restoredInline = meta?.inlineAppliedPlugin;
if (restoredInline?.pluginId !== appliedPlugin.pluginId) return null;
return mentionTokenPresent(text, restoredInline.label)
? { id: appliedPlugin.pluginId, label: restoredInline.label }
: null;
}
const designToolboxResourceIndex = useMemo<DesignToolboxResourceIndex>(
() => ({
skills,
plugins: pluginsForComposer,
mcpServers: enabledMcpServers,
mcpTemplates,
connectors,
projectFiles,
}),
[connectors, enabledMcpServers, mcpTemplates, pluginsForComposer, projectFiles, skills],
);
const composerMentionEntities = useMemo(
() =>
buildComposerMentionEntities({
connectors,
files: projectFiles,
mcpServers: enabledMcpServers,
plugins: pluginsForComposer,
skills,
staged,
workspaceContexts: selectedWorkspaceContexts,
}),
[connectors, enabledMcpServers, pluginsForComposer, projectFiles, selectedWorkspaceContexts, skills, staged],
);
// Resolve which tabs to surface in the consolidated tools popover.
// Plugins is always visible while a project is active so users can
// apply context without leaving the composer. MCP shows when wired by
// Catalog of supported slash commands. Each entry shows up in the
// popover when the user types `/` in the composer. The `insert`
// value is what we drop into the draft when the user picks the
// entry — usually the canonical command form with a trailing space
// ready for an argument.
const slashCommands = useMemo<SlashCommand[]>(() => {
const list: SlashCommand[] = [];
// External MCP servers — `/mcp` opens settings, `/mcp <id>` inserts a
// prompt-side hint nudging the model to use that server's tools. The
// hint flows through to the agent verbatim; the daemon already wired
// the MCP config into the agent's launch so the tools are callable.
if (onOpenMcpSettings) {
list.push({
id: 'mcp',
label: '/mcp',
insert: '/mcp ',
descKey: 'pet.slashPet',
icon: 'sliders',
argHint: 'open settings · <server-id> to insert hint',
});
}
for (const s of enabledMcpServers) {
list.push({
id: `mcp-${s.id}`,
label: `/mcp ${s.id}`,
insert: `Use the \`${s.id}\` MCP server tools. `,
descKey: 'pet.slashPet',
icon: 'sparkles',
argHint: s.label || s.transport,
});
}
if (researchAvailable) {
list.push({
id: 'search',