forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatComposer.tsx
More file actions
2682 lines (2594 loc) · 95.5 KB
/
ChatComposer.tsx
File metadata and controls
2682 lines (2594 loc) · 95.5 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 {
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { useI18n, useT } from '../i18n';
import type { Dict } from '../i18n/types';
import {
localizeSkillDescription,
localizeSkillName,
} from '../i18n/content';
import { useAnalytics } from '../analytics/provider';
import {
trackChatPanelClick,
trackFileUploadResult,
} from '../analytics/events';
import { deriveUploadCohort } from '../analytics/upload-tracking';
import { IMAGE_MODELS } from "../media/models";
import { projectRawUrl, uploadProjectFiles, openFolderDialog, fetchConnectors } from "../providers/registry";
import { patchProject } from "../state/projects";
import { fetchMcpServers } from "../state/mcp";
import type { McpServerConfig, McpTemplate } from "../state/mcp";
import { listPlugins } from "../state/projects";
import type { AppConfig, ChatAttachment, ChatCommentAttachment, ProjectFile, ProjectMetadata, SkillSummary } from "../types";
import type {
ContextItem,
ConnectorDetail,
InstalledPluginRecord,
PluginSourceKind,
ResearchOptions,
RunContextSelection,
} from '@open-design/contracts';
import { buildVisualAnnotationAttachment } from '../comments';
import { Icon } from "./Icon";
import { PluginDetailsModal } from "./PluginDetailsModal";
import { PluginsSection, type PluginsSectionHandle } from "./PluginsSection";
import { BUILT_IN_PETS, CUSTOM_PET_ID } from "./pet/pets";
import {
buildInlineMentionParts,
inlineMentionToken,
type InlineMentionEntity,
} from '../utils/inlineMentions';
import { isImeComposing } from '../utils/imeComposing';
import { ANNOTATION_EVENT, type AnnotationEventDetail } from "./PreviewDrawOverlay";
type TranslateFn = (key: keyof Dict, vars?: Record<string, string | number>) => string;
type ToolsTab = 'plugins' | 'skills' | 'mcp' | 'import' | 'pet';
type MentionTab = 'all' | 'plugins' | 'skills' | 'mcp' | 'connectors' | 'files';
const USER_PLUGIN_SOURCE_KINDS = new Set<PluginSourceKind>([
'user',
'project',
'marketplace',
'github',
'url',
'local',
]);
const COMPOSER_TEXTAREA_MIN_HEIGHT = 88;
const COMPOSER_TEXTAREA_MAX_HEIGHT = 184;
function composerTextareaMaxHeight(): number {
if (typeof window === 'undefined') return COMPOSER_TEXTAREA_MAX_HEIGHT;
return Math.max(
COMPOSER_TEXTAREA_MIN_HEIGHT,
Math.min(COMPOSER_TEXTAREA_MAX_HEIGHT, Math.round(window.innerHeight * 0.34)),
);
}
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';
}
interface Props {
projectId: string | null;
projectFiles: ProjectFile[];
streaming: boolean;
sendDisabled?: boolean;
initialDraft?: 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,
) => void;
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;
// Optional pet wiring — when present, the composer renders a small
// 🐾 button + popover so users can adopt / wake / tuck a pet without
// leaving chat. Typing `/pet` (or `/pet wake|tuck|<id>`) is parsed
// out of the draft and routed to the same handlers.
petConfig?: AppConfig['pet'];
onAdoptPet?: (petId: string) => void;
onTogglePet?: () => void;
onOpenPetSettings?: () => void;
researchAvailable?: boolean;
projectMetadata?: ProjectMetadata;
onProjectMetadataChange?: (metadata: ProjectMetadata) => void;
// SenseAudio BYOK image-model picker shown above the textarea. Hidden
// when the active chat protocol is anything other than 'senseaudio',
// so the composer stays clean for every other BYOK tab. 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;
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;
}
// Imperative handle so ancestors (e.g. example chips in ChatPane) can
// push text into the composer without owning its draft state.
export interface ChatComposerHandle {
setDraft: (text: string) => void;
focus: () => void;
}
export interface ChatSendMeta {
research?: ResearchOptions;
context?: RunContextSelection;
// 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[];
}
/**
* 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,
streaming,
sendDisabled = false,
initialDraft,
onEnsureProject,
commentAttachments = [],
onRemoveCommentAttachment,
skills = [],
onSend,
onStop,
onOpenMcpSettings,
petConfig,
onAdoptPet,
onTogglePet,
onOpenPetSettings,
researchAvailable = false,
projectMetadata,
onProjectMetadataChange,
byokApiProtocol,
byokImageModel,
onChangeByokImageModel,
currentSkillId = null,
onProjectSkillChange,
pinnedPluginId = null,
footerAccessory,
},
ref
) {
const t = useT();
const analytics = useAnalytics();
const [draft, setDraft] = useState(initialDraft ?? "");
// 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[]>([]);
const [stagedVisualComments, setStagedVisualComments] = useState<ChatCommentAttachment[]>([]);
const streamingAnnotationSendPendingRef = useRef(false);
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[]>([]);
const [stagedMcpServers, setStagedMcpServers] = useState<McpServerConfig[]>([]);
const [stagedConnectors, setStagedConnectors] = useState<ConnectorDetail[]>([]);
const [dragActive, setDragActive] = useState(false);
const [mention, setMention] = useState<{
q: string;
cursor: number;
} | null>(null);
const [composerScrollTop, setComposerScrollTop] = useState(0);
// 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;
cursor: number;
} | 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 pluginsSectionRef = useRef<PluginsSectionHandle | null>(null);
// Consolidated "tools" popover — a single dropdown anchored to the
// leading sliders icon that hosts MCP / Import / Pet quick actions and
// a shortcut to open the full Settings dialog. Replaces the previous
// row of three standalone buttons (which overflowed in narrow chats).
const [toolsOpen, setToolsOpen] = useState(false);
const [toolsTab, setToolsTab] = useState<ToolsTab>('plugins');
const fileInputRef = useRef<HTMLInputElement | null>(null);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const composingRef = useRef(false);
const toolsMenuRef = useRef<HTMLDivElement | null>(null);
const toolsTriggerRef = useRef<HTMLButtonElement | null>(null);
const petEnabled = Boolean(onAdoptPet && onTogglePet);
const linkedDirs = projectMetadata?.linkedDirs ?? [];
// 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(() => {
if (!toolsOpen) return;
function onPointer(e: MouseEvent) {
const target = e.target as Node;
if (toolsMenuRef.current?.contains(target)) return;
if (toolsTriggerRef.current?.contains(target)) return;
setToolsOpen(false);
}
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') setToolsOpen(false);
}
document.addEventListener('mousedown', onPointer);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onPointer);
document.removeEventListener('keydown', onKey);
};
}, [toolsOpen]);
// Lazy-fetch the user's external MCP servers list once on mount 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(() => {
let cancelled = false;
void (async () => {
const data = await fetchMcpServers();
if (cancelled || !data) return;
setMcpServers(data.servers);
setMcpTemplates(data.templates);
})();
return () => {
cancelled = true;
};
}, []);
// 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) return;
let cancelled = false;
void listPlugins().then((rows) => {
if (cancelled) return;
setInstalledPlugins(rows);
});
return () => {
cancelled = true;
};
}, [projectId]);
useEffect(() => {
let cancelled = false;
void fetchConnectors().then((rows) => {
if (cancelled) return;
setConnectors(rows.filter((connector) => connector.status === 'connected'));
});
return () => {
cancelled = true;
};
}, []);
// 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],
);
const composerMentionEntities = useMemo(
() =>
buildComposerMentionEntities({
connectors,
files: projectFiles,
mcpServers: enabledMcpServers,
plugins: pluginsForComposer,
skills,
staged,
}),
[connectors, enabledMcpServers, pluginsForComposer, projectFiles, skills, staged],
);
const composerMentionParts = useMemo(
() => buildInlineMentionParts(draft, composerMentionEntities),
[composerMentionEntities, draft],
);
function resizeTextarea() {
const ta = textareaRef.current;
if (!ta) return;
const maxHeight = composerTextareaMaxHeight();
ta.style.height = 'auto';
const nextHeight = Math.min(
Math.max(ta.scrollHeight, COMPOSER_TEXTAREA_MIN_HEIGHT),
maxHeight,
);
ta.style.height = `${nextHeight}px`;
ta.style.overflowY = ta.scrollHeight > maxHeight ? 'auto' : 'hidden';
}
useLayoutEffect(() => {
resizeTextarea();
}, [draft, composerMentionParts, staged.length, stagedSkills.length]);
useEffect(() => {
function onResize() {
resizeTextarea();
}
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
useEffect(() => {
setComposerScrollTop(textareaRef.current?.scrollTop ?? 0);
}, [composerMentionParts]);
// 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
// the parent (App); Import is always available. Pet controls stay out
// of the project context picker so the @ panel remains project-scoped.
const availableTabs = useMemo<ToolsTab[]>(() => {
const tabs: ToolsTab[] = [];
if (projectId) {
tabs.push('plugins');
tabs.push('skills');
}
if (onOpenMcpSettings) tabs.push('mcp');
tabs.push('import');
return tabs;
}, [projectId, onOpenMcpSettings]);
// When the popover opens, snap the active tab to the first available one
// so the user never lands on an empty / hidden tab if their config
// changes mid-session.
useEffect(() => {
if (!toolsOpen) return;
if (!availableTabs.includes(toolsTab)) {
const first = availableTabs[0];
if (first) setToolsTab(first);
}
}, [toolsOpen, availableTabs, toolsTab]);
// 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',
label: '/search',
insert: '/search ',
descKey: 'pet.slashSearch',
icon: 'sparkles',
argHint: t('pet.slashSearchArg'),
});
}
if (petEnabled) {
list.push(
{
id: 'pet',
label: '/pet',
insert: '/pet ',
descKey: 'pet.slashPet',
icon: 'sparkles',
argHint: 'wake | tuck | <petId>',
},
{
id: 'pet-wake',
label: '/pet wake',
insert: '/pet wake',
descKey: 'pet.slashPetWake',
icon: 'eye',
},
{
id: 'pet-tuck',
label: '/pet tuck',
insert: '/pet tuck',
descKey: 'pet.slashPetTuck',
icon: 'eye',
},
{
id: 'hatch',
label: '/hatch',
insert: '/hatch ',
descKey: 'pet.slashHatch',
icon: 'sparkles',
argHint: t('pet.slashHatchArg'),
},
);
}
return list;
}, [petEnabled, researchAvailable, t, enabledMcpServers, onOpenMcpSettings]);
const filteredSlash = useMemo(() => {
if (!slash) return [] as SlashCommand[];
const q = slash.q.toLowerCase();
if (!q) return slashCommands;
return slashCommands.filter((c) => c.label.toLowerCase().includes(q));
}, [slash, slashCommands]);
function pickSlash(cmd: SlashCommand) {
const ta = textareaRef.current;
if (!ta || !slash) return;
const before = draft.slice(0, slash.cursor);
const after = draft.slice(slash.cursor);
// Replace the in-flight `/<query>` token with the picked
// command's canonical insertion text.
const replaced = before.replace(/\/[^\s/]*$/, cmd.insert);
const next = replaced + after;
setDraft(next);
setSlash(null);
requestAnimationFrame(() => {
ta.focus();
const pos = replaced.length;
ta.setSelectionRange(pos, pos);
});
}
// Expand a `/hatch <concept>` draft into the canonical hatch-pet
// skill prompt before sending. Returns null when the draft is not a
// hatch command so the caller can fall through to the regular
// submit path.
function expandHatchCommand(input: string): string | null {
const m = /^\/hatch(?:\s+([\s\S]*))?$/i.exec(input.trim());
if (!m) return null;
const concept = m[1]?.trim() ?? '';
const intro = concept
? `Hatch a Codex-compatible animated pet for me. Concept: ${concept}.`
: 'Hatch a Codex-compatible animated pet for me.';
return [
intro,
'',
'Use the @hatch-pet skill end-to-end:',
'1. Generate the base look with $imagegen.',
'2. Generate every row strip (idle, running-right, waving, jumping, failed, waiting, running, review).',
'3. Mirror running-left from running-right only when the design is symmetric.',
'4. Run the deterministic scripts (extract / compose / validate / contact-sheet / videos).',
'5. Package the result into ${CODEX_HOME:-$HOME/.codex}/pets/<pet-name>/ with pet.json + spritesheet.webp.',
'',
'When the spritesheet is saved, tell me the absolute path and the pet folder name. I will adopt it from Settings → Pets → Recently hatched.',
].join('\n');
}
// `/mcp` (no arg) opens settings on the External MCP tab — pure UX hook,
// never sent to the agent. `/mcp <id>` is intentionally NOT intercepted
// here: the slash palette already replaces it with a natural-language
// hint sentence ("Use the `<id>` MCP server tools."), and the user is
// expected to keep typing the rest of the prompt before sending.
function tryHandleMcpSlash(): boolean {
if (!onOpenMcpSettings) return false;
const trimmed = draft.trim();
if (!/^\/mcp\s*$/i.test(trimmed)) return false;
onOpenMcpSettings();
setDraft('');
return true;
}
function expandSearchCommand(input: string): { prompt: string; query: string } | null {
const m = /^\/search(?:\s+([\s\S]*))?$/i.exec(input.trim());
if (!m) return null;
const query = m[1]?.trim() ?? '';
if (!query) return null;
return {
query,
prompt: [
`Search for: ${query}`,
'',
'Before answering, your first tool action must be the OD research command for your shell.',
'POSIX: "$OD_NODE_BIN" "$OD_BIN" research search --query "<search query>" --max-sources 5',
'PowerShell: & $env:OD_NODE_BIN $env:OD_BIN research search --query "<search query>" --max-sources 5',
'cmd.exe: "%OD_NODE_BIN%" "%OD_BIN%" research search --query "<search query>" --max-sources 5',
'Use the canonical query below as the exact search query, with safe quoting for your shell.',
'',
'Canonical query:',
'',
'```text',
query.replace(/```/g, '`\u200b`\u200b`'),
'```',
'If the OD command fails because Tavily is not configured or unavailable, report that error, then use your own search capability as fallback and label the fallback clearly.',
'After the command returns JSON or fallback search results, write a reusable Markdown report into Design Files at `research/<safe-query-slug>.md` or another fresh project-relative path.',
'The report must include the query, fetched time, short summary, key findings, source list with [1], [2] citations, and a note that source content is external untrusted evidence.',
'Then summarize the findings with citations by source index and mention the Markdown report path.',
].join('\n'),
};
}
// Parse a `/pet [arg]` slash command out of the draft. Recognized
// forms: `/pet` (toggle wake/tuck), `/pet wake`, `/pet tuck`,
// `/pet adopt` (open settings), or `/pet <id>` to adopt a built-in
// by id. The slash is stripped from the draft on a successful match
// so the user does not accidentally send the command to the agent.
function tryHandlePetSlash(): boolean {
if (!petEnabled) return false;
const trimmed = draft.trim();
const match = /^\/pet(?:\s+(\S+))?$/i.exec(trimmed);
if (!match) return false;
const arg = match[1]?.toLowerCase();
if (!arg || arg === 'toggle') {
onTogglePet?.();
} else if (arg === 'wake' || arg === 'show') {
if (petConfig?.adopted) {
if (!petConfig.enabled) onTogglePet?.();
} else {
onOpenPetSettings?.();
}
} else if (arg === 'tuck' || arg === 'hide') {
if (petConfig?.enabled) onTogglePet?.();
} else if (arg === 'adopt' || arg === 'settings' || arg === 'change') {
onOpenPetSettings?.();
} else if (arg === CUSTOM_PET_ID) {
onAdoptPet?.(CUSTOM_PET_ID);
} else {
const pet = BUILT_IN_PETS.find((p) => p.id === arg);
if (pet) {
onAdoptPet?.(pet.id);
} else {
return false;
}
}
setDraft('');
return true;
}
useImperativeHandle(
ref,
() => ({
setDraft: (text: string) => {
setDraft(text);
seededRef.current = true;
requestAnimationFrame(() => {
const ta = textareaRef.current;
if (!ta) return;
ta.focus();
const pos = text.length;
ta.setSelectionRange(pos, pos);
});
},
focus: () => {
textareaRef.current?.focus();
},
}),
[]
);
function reset() {
setDraft("");
setStaged([]);
setStagedVisualComments([]);
setStagedSkills([]);
setStagedMcpServers([]);
setStagedConnectors([]);
setUploadError(null);
setMention(null);
setSlash(null);
}
function currentCommentAttachments(extra: ChatCommentAttachment[] = []): ChatCommentAttachment[] {
return [...commentAttachments, ...stagedVisualComments, ...extra];
}
function setStreamingAnnotationSendPending(value: boolean) {
streamingAnnotationSendPendingRef.current = value;
setStreamingAnnotationSendPendingState(value);
}
function currentRunContextMeta(): ChatSendMeta | undefined {
const skillIds = stagedSkills.map((s) => s.id);
const mcpServerIds = stagedMcpServers.map((s) => s.id);
const connectorIds = stagedConnectors.map((c) => c.id);
const context: RunContextSelection = {
...(skillIds.length > 0 ? { skillIds } : {}),
...(mcpServerIds.length > 0 ? { mcpServerIds } : {}),
...(connectorIds.length > 0 ? { connectorIds } : {}),
};
const meta: ChatSendMeta = {
...(skillIds.length > 0 ? { skillIds } : {}),
...(Object.keys(context).length > 0 ? { context } : {}),
};
return Object.keys(meta).length > 0 ? meta : undefined;
}
function sendComposedTurn(
prompt: string,
attachments: ChatAttachment[],
nextCommentAttachments: ChatCommentAttachment[],
meta?: ChatSendMeta,
): boolean {
setStreamingAnnotationSendPending(false);
if (!prompt && attachments.length === 0 && nextCommentAttachments.length === 0) return false;
onSend(prompt, attachments, nextCommentAttachments, meta);
reset();
return true;
}
async function insertSkillMention(skill: SkillSummary) {
const applied = await applyProjectSkill(skill);
if (!applied) return;
replaceMentionWithText(`${inlineMentionToken(skill.name)} `);
}
function removeStagedSkill(id: string) {
setStagedSkills((prev) => prev.filter((s) => s.id !== id));
// Also strip the matching `@<id>` token from the draft so the chip
// and the textarea stay in sync. We allow trailing whitespace to be
// collapsed too.
setDraft((d) =>
d
.replace(new RegExp(`(^|\\s)@${escapeRegExp(id)}(\\s|$)`, 'g'), '$1$2')
.replace(/\s{2,}/g, ' '),
);
}
async function ensureProject(): Promise<string | null> {
if (projectId) return projectId;
return onEnsureProject();
}
async function uploadFiles(files: File[]) {
if (files.length === 0) return;
const id = await ensureProject();
if (!id) return;
setUploading(true);
setUploadError(null);
// Cohort math is identical to the Design Files Upload button; see
// `analytics/upload-tracking.ts`. v2 doc fires one
// file_upload_result per surface so this path reports
// `page_name='chat_panel'` / `area='chat_composer'`.
const cohort = deriveUploadCohort(files);
try {
const result = await uploadProjectFiles(id, files);
if (result.uploaded.length > 0) {
setStaged((s) => [...s, ...result.uploaded]);
}
const partial = result.failed.length > 0;
if (partial) {
const failedCount = result.failed.length;
const uploadedCount = result.uploaded.length;
const detail = result.error ? ` (${result.error})` : '';
setUploadError(
uploadedCount > 0
? `Attached ${uploadedCount} file(s), but ${failedCount} failed${detail}.`
: `Attachment upload failed for ${failedCount} file(s)${detail}.`,
);
console.warn('Some attachments failed to upload', result.failed);
}
trackFileUploadResult(analytics.track, {
page_name: 'chat_panel',
area: 'chat_composer',
project_id: id,
...cohort,
result: partial ? 'failed' : 'success',
...(partial && result.error ? { error_code: result.error } : {}),
});
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
setUploadError(`Attachment upload failed (${detail}).`);
trackFileUploadResult(analytics.track, {
page_name: 'chat_panel',
area: 'chat_composer',
project_id: id,
...cohort,
result: 'failed',
error_code: detail,
});
} finally {
setUploading(false);
}
}
useEffect(() => {
function onAnnotation(e: Event) {
const detail = (e as CustomEvent<AnnotationEventDetail>).detail;
if (!detail) return;
void (async () => {
let uploaded: ChatAttachment[] = [];
let visualAttachmentInput: Parameters<typeof buildVisualAnnotationAttachment>[0] | null = null;
let visualAttachment: ChatCommentAttachment | null = null;
if (detail.file) {
const id = await ensureProject();
if (!id) return;
setUploading(true);
try {
const result = await uploadProjectFiles(id, [detail.file]);
if (result.uploaded.length > 0) {
uploaded = result.uploaded;
if (detail.action !== 'send') {
setStaged((s) => [...s, ...uploaded]);
}
const screenshot = uploaded[0];
if (screenshot && detail.markKind && detail.bounds) {
visualAttachmentInput = {
order: 1,
idSeed: screenshot.path,
screenshotPath: screenshot.path,
markKind: detail.markKind,
note: detail.note,
bounds: detail.bounds,
target: detail.target
? {
filePath: detail.target.filePath || detail.filePath || screenshot.path,
elementId: detail.target.elementId,
selector: detail.target.selector,
label: detail.target.label,
text: detail.target.text,
position: detail.target.position,
htmlHint: detail.target.htmlHint,
}
: {
filePath: detail.filePath || screenshot.path,
position: detail.bounds,
},
};
if (detail.action !== 'send') {
setStagedVisualComments((current) => [
...current,
buildVisualAnnotationAttachment({
...visualAttachmentInput!,
order: commentAttachments.length + current.length + 1,
}),
]);
}
}
}
if (result.failed.length > 0) {
const detailText = result.error ? ` (${result.error})` : '';
setUploadError(`Attachment upload failed for ${result.failed.length} file(s)${detailText}.`);
}
} finally {
setUploading(false);
}
}
if (detail.action === 'send') {
if (streaming) {
if (uploaded.length > 0) setStaged((s) => [...s, ...uploaded]);
if (visualAttachmentInput) {
setStagedVisualComments((current) => [
...current,
buildVisualAnnotationAttachment({
...visualAttachmentInput!,
order: commentAttachments.length + current.length + 1,
}),
]);
}
if (detail.note) setDraft((d) => (d ? `${d}\n${detail.note}` : detail.note));
setStreamingAnnotationSendPending(true);
textareaRef.current?.focus();
return;
}
if (visualAttachmentInput) {
visualAttachment = buildVisualAnnotationAttachment({
...visualAttachmentInput,
order: commentAttachments.length + stagedVisualComments.length + 1,
});
}
const prompt = [draft.trim(), detail.note].filter(Boolean).join('\n');
const attachments = [...staged, ...uploaded];
const nextCommentAttachments = currentCommentAttachments(visualAttachment ? [visualAttachment] : []);
sendComposedTurn(prompt, attachments, nextCommentAttachments, currentRunContextMeta());
return;
}
if (detail.note) {
setDraft((d) => (d ? `${d}\n${detail.note}` : detail.note));
textareaRef.current?.focus();
}
})();
}
window.addEventListener(ANNOTATION_EVENT, onAnnotation);
return () => window.removeEventListener(ANNOTATION_EVENT, onAnnotation);
}, [
commentAttachments,
draft,
onSend,
projectId,
staged,
stagedConnectors,
stagedMcpServers,
stagedSkills,
stagedVisualComments,
streaming,
]);
useEffect(() => {
if (!streamingAnnotationSendPending || !streamingAnnotationSendPendingRef.current) return;
if (streaming || sendDisabled) return;
const prompt = draft.trim();
sendComposedTurn(prompt, staged, currentCommentAttachments(), currentRunContextMeta());
}, [
commentAttachments,
draft,
onSend,
sendDisabled,
staged,
stagedConnectors,
stagedMcpServers,
stagedSkills,
stagedVisualComments,
streaming,
streamingAnnotationSendPending,
]);
function handlePaste(e: React.ClipboardEvent<HTMLTextAreaElement>) {
const items = Array.from(e.clipboardData?.items ?? []);
const files: File[] = [];
for (const item of items) {
if (item.kind === "file") {
const f = item.getAsFile();
if (f) files.push(f);
}
}
if (files.length > 0) {
e.preventDefault();
void uploadFiles(files);
}
}
function handleDrop(e: React.DragEvent<HTMLDivElement>) {
e.preventDefault();
setDragActive(false);
const files = Array.from(e.dataTransfer.files ?? []);
if (files.length > 0) void uploadFiles(files);
}
async function handleLinkFolder() {
if (!projectId) return;
const selected = await openFolderDialog();
if (!selected) return;
const base = projectMetadata ?? { kind: 'prototype' as const };
const existing = base.linkedDirs ?? [];
if (existing.includes(selected)) return;
const metadata: ProjectMetadata = { ...base, linkedDirs: [...existing, selected] };
const result = await patchProject(projectId, { metadata });
if (result?.metadata) onProjectMetadataChange?.(result.metadata);
}
async function handleUnlinkFolder(dir: string) {
if (!projectId) return;
const base = projectMetadata ?? { kind: 'prototype' as const };
const existing = base.linkedDirs ?? [];
const metadata: ProjectMetadata = { ...base, linkedDirs: existing.filter((d) => d !== dir) };
const result = await patchProject(projectId, { metadata });
if (result?.metadata) onProjectMetadataChange?.(result.metadata);
}
function handleChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
const value = e.target.value;
const cursor = e.target.selectionStart;
setDraft(value);
// Keep the staged-skill chips in sync with the draft. If the user
// hand-deletes an `@<id>` token from the textarea, the chip must
// disappear too — otherwise submit() would still forward that id in
// skillIds and the daemon would compose a skill the prompt no
// longer references. Mirror the removeStagedSkill() boundary
// (whitespace or string edge) so partial matches don't keep a chip
// alive accidentally. We do not run the same prune for `staged`
// file attachments because users frequently attach files via the
// upload button without leaving an `@<path>` token in the draft.
setStagedSkills((prev) =>
prev.filter((s) =>
new RegExp(`(^|\\s)@${escapeRegExp(s.id)}(\\s|$)`).test(value),