-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathindex.tsx
More file actions
1039 lines (931 loc) · 37.3 KB
/
Copy pathindex.tsx
File metadata and controls
1039 lines (931 loc) · 37.3 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 { getAgentManager, useAgentChat, type UIMessage } from '@automattic/agenttic-client';
import {
type Suggestion,
type MarkdownComponents,
type MarkdownExtensions,
} from '@automattic/agenttic-ui';
import { useSelect } from '@wordpress/data';
import { useState, useCallback, useMemo, useEffect, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useNavigate } from 'react-router-dom';
import { LOCAL_TOOL_RUNNING_MESSAGE } from '../../constants';
import { useAgentsManagerContext } from '../../contexts';
import { useRegisterCustomActions } from '../../hooks/custom-actions';
import useAgentTraceIds from '../../hooks/use-agent-trace-ids';
import { useBroadcastConversationActivity } from '../../hooks/use-broadcast-conversation-activity';
import useCheckpointAction from '../../hooks/use-checkpoint-action';
import useConversation from '../../hooks/use-conversation';
import useCopyAction from '../../hooks/use-copy-action';
import { usePageOrSiteEditorSurface } from '../../hooks/use-empty-view-suggestions';
import useFeedbackAction from '../../hooks/use-feedback-action';
import { useImageUpload } from '../../hooks/use-image-upload';
import useRegenerateAction from '../../hooks/use-regenerate-action';
import useSaveNewChatRoute from '../../hooks/use-save-new-chat-route';
import useSourcesAction from '../../hooks/use-sources-action';
import useZoomAction from '../../hooks/use-zoom-action';
import { markSessionUsed } from '../../utils/agent-session';
import convertToolMessagesToComponents, {
type AgentsManagerUIMessage,
} from '../../utils/convert-tool-messages-to-components';
import {
consumeNextMessageExternalContextEntries,
removeExternalContextCard,
removeExternalContextEntry,
type ExternalContextCard,
type ExternalContextCardAction,
} from '../../utils/external-context';
import { isReaderChatAgent } from '../../utils/is-reader-chat-agent';
import { mergeEmptyViewSuggestions } from '../../utils/merge-empty-view-suggestions';
import { getOrchestratorErrorMessage } from '../../utils/orchestrator-error-message';
import { persistLastActivity } from '../../utils/persist-last-activity';
import { getReaderChatErrorMessage } from '../../utils/reader-chat-error-message';
import { isShowComponentTool } from '../../utils/show-component-tools';
import { recordBigSkyTracksEvent } from '../../utils/tracks';
import AgentChat from '../agent-chat';
import { type Options as ChatHeaderOptions } from '../chat-header';
import type { BigSkyMessage } from '../../types';
import type {
NavigationContinuationHook,
AbilitiesSetupHook,
GetChatComponent,
UseSuggestionsHook,
SiteBuildUtils,
UseCheckpointHook,
ProviderCapabilities,
} from '../../utils/load-external-providers';
function getLatestAgentMessageId( messages: UIMessage[] ): string | null {
for ( let index = messages.length - 1; index >= 0; index-- ) {
if ( messages[ index ].role === 'agent' ) {
return messages[ index ].id;
}
}
return null;
}
/**
* Pipe-delimited list of suggestion ids (e.g. `|id1|id2|`), matching Big Sky's
* `suggestions` / `available_suggestions` tracks-prop format.
*/
function formatSuggestionIds( suggestions: Suggestion[] ): string {
return '|' + suggestions.map( ( s ) => s.id ).join( '|' ) + '|';
}
/**
* Get `option_id` by matching Agenttic's selected prompt to the original options.
* The current tracked dropdowns have an empty parent prompt, so Agenttic copies the
* selected option's configured value unchanged. For example, selecting Formal
* returns that option's value, which maps directly to the stable id `formal`.
* Provider tests enforce the empty parent prompt requirement.
*/
function getSelectedOptionId(
selectedSuggestion: Suggestion,
availableSuggestions: Suggestion[]
): string | undefined {
const originalSuggestion = availableSuggestions.find(
( suggestion ) => suggestion.id === selectedSuggestion.id
);
return originalSuggestion?.options?.find(
( option ) => option.value === selectedSuggestion.prompt
)?.id;
}
function getToolMessageData( message: Pick< UIMessage, 'content' > ):
| {
toolId?: string;
toolCallId?: string;
componentType?: string;
summary?: string;
}
| undefined {
const firstText = message.content?.[ 0 ]?.text;
if ( ! firstText ) {
return undefined;
}
try {
const parsed = JSON.parse( firstText );
return {
toolId: parsed?.tool_id,
toolCallId: parsed?.tool_call_id,
componentType: parsed?.data?.type,
summary: parsed?.data?.summary,
};
} catch ( _error ) {
return undefined;
}
}
function isShowComponentMessage( message: Pick< UIMessage, 'content' > ): boolean {
const toolData = getToolMessageData( message );
return isShowComponentTool( toolData?.toolId );
}
function getShowComponentIdentity( message: Pick< UIMessage, 'content' > ): string | undefined {
const toolData = getToolMessageData( message );
if ( ! toolData || ! isShowComponentTool( toolData.toolId ) ) {
return undefined;
}
return [ toolData.toolCallId, toolData.componentType, toolData.summary ]
.filter( Boolean )
.join( '|' );
}
function convertBigSkyMessageToUIMessage( message: BigSkyMessage ): UIMessage {
const uiMessage = {
// Keep Big Sky message properties without explicit mapping to keep linter happy.
// Big Sky messages sometimes have a `context` field used by the site build to
// show the progress indicator.
...message,
id: message.id,
role: message.role === 'assistant' ? 'agent' : 'user',
content: message.content,
timestamp: message.created_at ? message.created_at * 1000 : Date.now(),
archived: message.archived ?? false,
showIcon: message.showIcon ?? true,
} as UIMessage;
return uiMessage;
}
interface Props {
/** Suggestions displayed when the chat is empty. */
emptyViewSuggestions: Suggestion[];
/** Indicates if the chat is docked in the sidebar. */
isDocked: boolean;
/** Indicates if the chat is expanded (floating mode). */
isOpen: boolean;
/** Indicates if suggestions are visible in the current layout. */
suggestionsVisible: boolean;
/** Called when the chat is closed. */
onClose: () => void;
/** Called when the chat is expanded (floating mode). */
onExpand: () => void;
/** Chat header menu options. */
chatHeaderOptions: ChatHeaderOptions;
/** Custom components for rendering markdown. */
markdownComponents: MarkdownComponents;
/** Custom markdown extensions. */
markdownExtensions: MarkdownExtensions;
/** Indicates if the floating chat is in compact mode. */
isCompactMode: boolean;
/** Navigation continuation hook for post-navigation conversation resumption. */
useNavigationContinuation?: NavigationContinuationHook;
/** Hook for setting up abilities that utilize React context. Invoked after custom actions registration. */
useAbilitiesSetup?: AbilitiesSetupHook;
/** Hook for providing dynamic suggestions based on context (e.g., selected block). */
useSuggestions?: UseSuggestionsHook;
/** Get a chat component by type for rendering in agent messages. */
getChatComponent?: GetChatComponent;
/** Utilities for site building flow (e.g., progress tracking, site preview). */
siteBuildUtils?: SiteBuildUtils;
/** Hook for saving and restoring editor state so that AI actions can be undone. */
useCheckpoint?: UseCheckpointHook;
/** Optional capability flags declared by one or more loaded providers. */
capabilities?: ProviderCapabilities;
/** Called when the has-messages state changes. */
onHasMessagesChange: ( hasMessages: boolean ) => void;
}
export default function OrchestratorChat( {
emptyViewSuggestions,
isDocked,
isOpen,
suggestionsVisible,
onClose,
onExpand,
chatHeaderOptions,
markdownComponents,
markdownExtensions,
isCompactMode,
useNavigationContinuation,
useAbilitiesSetup,
useSuggestions,
getChatComponent,
siteBuildUtils,
useCheckpoint,
capabilities,
onHasMessagesChange,
}: Props ) {
const { agentConfig, getActiveSessionId, siteKey } = useAgentsManagerContext();
const navigate = useNavigate();
const [ inputValue, setInputValue ] = useState( '' );
const [ isThinking, setIsThinking ] = useState( false );
const [ thinkingMessage, setThinkingMessage ] = useState< string | null >( null );
const [ isBuildingSite, setIsBuildingSite ] = useState( false );
const [ deletedMessageIds, setDeletedMessageIds ] = useState< Set< string > >( new Set() );
const [ retainedShowComponentMessages, setRetainedShowComponentMessages ] = useState<
Map< string, UIMessage >
>( new Map() );
const [ isRegenerating, setIsRegenerating ] = useState( false );
const [ hasUserSentMessage, setHasUserSentMessage ] = useState( false );
const currentPostId = useSelect( ( select ) => {
const editor = select( 'core/editor' ) as { getCurrentPostId?: () => number | string };
return editor?.getCurrentPostId?.();
}, [] );
const selectedBlockType = useSelect( ( select ) => {
try {
const blockEditor = select( 'core/block-editor' ) as {
getSelectedBlock?: () => { name?: unknown } | null;
};
const blockName = blockEditor?.getSelectedBlock?.()?.name;
return typeof blockName === 'string' && blockName ? blockName : undefined;
} catch {
return undefined;
}
}, [] );
const { isPageOrSiteEditorSurface: groupWritingSuggestions } = usePageOrSiteEditorSurface();
const {
addMessage,
messages,
suggestions,
isProcessing,
error,
loadMessages,
onSubmit,
abortCurrentRequest,
clearSuggestions,
registerSuggestions,
registerMessageActions,
getRegenerateHandler,
progressMessage,
} = useAgentChat( agentConfig! );
const messagesRef = useRef( messages );
const getTraceIdForMessage = useAgentTraceIds( agentConfig );
const previousMessagesRef = useRef( messages );
const showComponentOrderRef = useRef< Map< string, number > >( new Map() );
const nextShowComponentOrderRef = useRef( 0 );
const wasProcessingRef = useRef( isProcessing );
messagesRef.current = messages;
// Drop all retained placeholders, keeping the map reference stable when
// already empty so no re-render is triggered.
const clearRetainedShowComponentMessages = useCallback( () => {
setRetainedShowComponentMessages( ( previousRetainedMessages ) =>
previousRetainedMessages.size > 0 ? new Map() : previousRetainedMessages
);
}, [] );
// A regeneration is finished once its streaming turn settles — either the new
// response arrives or an error restores the previous one. Re-enable component
// retention then so transient drops on later turns are covered again.
useEffect( () => {
const wasProcessing = wasProcessingRef.current;
wasProcessingRef.current = isProcessing;
if ( isRegenerating && wasProcessing && ! isProcessing ) {
setIsRegenerating( false );
}
}, [ isProcessing, isRegenerating ] );
// While a regeneration runs, the component being regenerated is deliberately
// dropped from the live messages (Agenttic sends `preserveUiOnlyMessages:
// false`), so retention must not resurrect the old picker as a stale copy.
const handleRegenerate = useCallback(
( message?: UIMessage ) => {
const handler = getRegenerateHandler?.( message );
if ( ! handler ) {
return handler;
}
return async () => {
setIsRegenerating( true );
// Drop any retained placeholders up front; the turn is being
// rewound, so a leftover picker would otherwise reappear once
// regeneration settles if the new response omits the component.
clearRetainedShowComponentMessages();
await handler();
};
},
[ clearRetainedShowComponentMessages, getRegenerateHandler ]
);
const getShowComponentOrder = useCallback( ( message: UIMessage ): number | undefined => {
const identity = getShowComponentIdentity( message );
if ( ! identity ) {
return undefined;
}
const existingOrder = showComponentOrderRef.current.get( identity );
if ( existingOrder !== undefined ) {
return existingOrder;
}
const nextOrder = nextShowComponentOrderRef.current++;
showComponentOrderRef.current.set( identity, nextOrder );
return nextOrder;
}, [] );
useEffect( () => {
const previousMessages = previousMessagesRef.current;
// A full history replacement (server hydration, clearing the chat) swaps
// every message id at once. Nothing in it was transiently dropped, and
// the same picker can carry a different identity in loaded history than
// it did live — retaining across the swap would show it as a duplicate.
const previousMessageIds = new Set( previousMessages.map( ( message ) => message.id ) );
const isHistoryReplaced =
previousMessages.length > 0 &&
! messages.some( ( message ) => previousMessageIds.has( message.id ) );
// While regenerating, the dropped component is being replaced, not lost —
// don't retain it either. Keep the ref current so the next run compares
// against the latest messages.
if ( isRegenerating || isHistoryReplaced ) {
if ( isHistoryReplaced ) {
clearRetainedShowComponentMessages();
}
previousMessagesRef.current = messages;
return;
}
messages.filter( isShowComponentMessage ).forEach( getShowComponentOrder );
const currentShowComponentIdentities = new Set(
messages.filter( isShowComponentMessage ).map( getShowComponentIdentity ).filter( Boolean )
);
const retainedCandidates = previousMessages.filter( ( previousMessage ) => {
const identity = getShowComponentIdentity( previousMessage );
return !! identity && ! currentShowComponentIdentities.has( identity );
} );
if ( retainedCandidates.length > 0 ) {
setRetainedShowComponentMessages( ( previousRetainedMessages ) => {
const nextRetainedMessages = new Map( previousRetainedMessages );
let changed = false;
for ( const message of retainedCandidates ) {
const identity = getShowComponentIdentity( message );
// One placeholder per identity, so a component that drops and
// returns refreshes in place instead of stacking another copy.
const retainedId = `retained-${ identity }`;
if ( ! nextRetainedMessages.has( retainedId ) ) {
nextRetainedMessages.set( retainedId, { ...message, id: retainedId } );
changed = true;
}
}
return changed ? nextRetainedMessages : previousRetainedMessages;
} );
}
previousMessagesRef.current = messages;
}, [ clearRetainedShowComponentMessages, getShowComponentOrder, messages, isRegenerating ] );
// Reader-chat sessions are short (usually < 50 messages) — don't waste
// time paginating 10 pages deep. One page covers typical use.
const isReaderChat = isReaderChatAgent( agentConfig?.agentId );
const shouldLoadConversation =
! isReaderChat || ( ! hasUserSentMessage && messages.length === 0 && ! isProcessing );
const chatError = isReaderChat
? getReaderChatErrorMessage( error )
: getOrchestratorErrorMessage( error );
const { isLoading: isLoadingConversation } = useConversation( {
maxPages: isReaderChat ? 1 : 10,
enabled: shouldLoadConversation,
onSuccess: ( loadedMessages, serverSessionId ) => {
if ( isReaderChat && ( hasUserSentMessage || messages.length > 0 || isProcessing ) ) {
return;
}
// Update the UI with the loaded messages
loadMessages( loadedMessages );
// Make sure future messages go to the right session
getAgentManager().updateSessionId( agentConfig!.agentId, serverSessionId );
// Sync local session ID with the server's
if ( agentConfig!.sessionId !== serverSessionId ) {
navigate( '/chat', { state: { sessionId: serverSessionId }, replace: true } );
}
},
} );
// Use dynamic suggestions from the external provider (e.g., Big Sky block-based suggestions)
const maxDynamicSuggestions = isDocked ? undefined : 3;
const dynamicSuggestions = useSuggestions?.( maxDynamicSuggestions, {
suggestionsVisible,
} );
const dynamicSuggestionsList = dynamicSuggestions?.suggestions ?? [];
const replaceEmptyViewSuggestions = dynamicSuggestions?.replaceEmptyViewSuggestions === true;
const dynamicSuggestionsKey = JSON.stringify(
dynamicSuggestionsList.map( ( s ) => [ s.id, s.label, s.prompt ] )
);
const contextualSuggestionIds = useMemo(
() =>
replaceEmptyViewSuggestions
? new Set( dynamicSuggestionsList.map( ( suggestion ) => suggestion.id ) )
: new Set< string >(),
// Track suggestion content rather than an unstable provider array.
// eslint-disable-next-line react-hooks/exhaustive-deps
[ dynamicSuggestionsKey, replaceEmptyViewSuggestions ]
);
// Register dynamic suggestions whenever they change
useEffect( () => {
if ( dynamicSuggestionsList.length > 0 ) {
registerSuggestions?.( dynamicSuggestionsList );
} else {
// Clear suggestions when there are none
clearSuggestions?.();
}
// Track suggestion content, not array identity. Some merged providers
// return a fresh empty array on each render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ dynamicSuggestionsKey, registerSuggestions, clearSuggestions ] );
// Persist the chat route so the conversation can be resumed later.
useSaveNewChatRoute( hasUserSentMessage );
// Register an "Undo" action on agent messages with checkpoints.
const checkpoint = useCheckpoint?.();
const getCheckpointActionsForMessage = useCheckpointAction( registerMessageActions, checkpoint );
// Register thumbs-up/down feedback actions on agent messages.
const { showFeedbackInput, submitFeedbackText, resetFeedback, getFeedbackActionsForMessage } =
useFeedbackAction( {
registerMessageActions,
messages,
getTraceIdForMessage,
} );
// Add Agenttic's built-in regenerate action on agent messages for providers
// that opt in. Computed during render alongside copy/feedback so the icon
// appears in the same paint rather than a commit later.
const getRegenerateActionsForMessage = useRegenerateAction( {
enabled: capabilities?.supportsRegenerateAction === true,
getRegenerateHandler: handleRegenerate,
} );
// Add a "Copy" action on plain-text agent messages.
const getCopyActionsForMessage = useCopyAction();
// Register zoom-in/zoom-out actions on agent messages.
useZoomAction( registerMessageActions );
// Register a "Sources" action on agent messages with sources data.
useSourcesAction( registerMessageActions, ! isReaderChat );
const imageUploadResult = useImageUpload();
// Reader chat is a public blog frontend — visitors can't upload media.
const imageUpload = isReaderChat ? undefined : imageUploadResult;
const pendingImages = imageUpload?.pendingImages || [];
const uploadImagesToWordPress = imageUpload?.uploadImagesToWordPress;
const isUploadingImages = imageUpload?.isUploadingImages ?? false;
const [ uploadError, setUploadError ] = useState< string | null >( null );
const setChatInput = useCallback( ( value: string ) => {
if ( typeof value !== 'string' ) {
return;
}
setInputValue( value );
const textarea = document.querySelector< HTMLTextAreaElement >(
'.agenttic [data-slot="chat-input"] [data-slot="textarea"]'
);
if ( textarea ) {
textarea.focus();
textarea.setSelectionRange( value.length, value.length );
}
}, [] );
// Whether the last `onSubmitWithImages` call actually dispatched — dropped,
// aborted, and failed sends deliberately leave the composer intact.
const submitDispatchedRef = useRef( false );
// Synchronous lock for the upload phase: same-tick re-entry (double-click,
// programmatic submit) lands before the `isUploadingImages` state does.
const isUploadingRef = useRef( false );
const onSubmitWithImages = useCallback(
async ( message: string ) => {
submitDispatchedRef.current = false;
// The composer is committed while a batch uploads — drop re-entrant
// sends (suggestion clicks, programmatic submits) instead of
// interleaving a second message.
if ( isUploadingRef.current || isUploadingImages ) {
return;
}
setHasUserSentMessage( true );
setUploadError( null );
persistLastActivity( siteKey );
recordBigSkyTracksEvent( 'chat_input_send_message', {
message_length: message?.length || 0,
has_images: pendingImages.length > 0,
} );
let imageData;
if ( pendingImages.length > 0 && uploadImagesToWordPress ) {
isUploadingRef.current = true;
try {
// Agenttic clears the (controlled) input on submit. When the message
// came from the composer, keep it visible while images upload: wait a
// microtask so the restore lands after that clear, and re-place the
// caret at the end (the clear leaves it at 0). Suggestion-driven and
// programmatic submits leave any draft alone. Agenttic dispatches the
// trimmed draft, hence the trim-compare.
if ( inputValue.trim() === message ) {
await Promise.resolve();
setChatInput( message );
}
const mediaObjects = await uploadImagesToWordPress();
recordBigSkyTracksEvent( 'file_upload_success', {
count: mediaObjects.length,
} );
imageData = mediaObjects.map( ( media ) => ( {
url: media.url,
metadata: {
id: media.id, // WordPress attachment ID
title: media.title,
fileName: media.fileName,
fileType: media.fileType,
fileSize: media.fileSize,
dimensions: media.dimensions,
uploadDate: media.uploadDate,
alt: media.alt,
caption: media.caption,
},
} ) );
} catch ( caughtError ) {
// Stop during upload: the previews are restored and a
// composer-typed message stays in the input — the composer is
// back to its pre-send state.
if ( caughtError instanceof Error && caughtError.name === 'AbortError' ) {
recordBigSkyTracksEvent( 'file_upload_cancel', {
count: pendingImages.length,
} );
return;
}
recordBigSkyTracksEvent( 'file_upload_error', {
count: pendingImages.length,
} );
setUploadError(
__( 'Failed to upload images. Please try again.', __i18n_text_domain__ )
);
return;
} finally {
isUploadingRef.current = false;
}
// The message dispatches now — clear the input only when it still
// holds this message (a suggestion-driven send may have left an
// unrelated draft in it).
setInputValue( ( currentValue ) => ( currentValue === message ? '' : currentValue ) );
}
submitDispatchedRef.current = true;
try {
// Images dispatch via agenttic's `imageUrls` option — the resulting
// `FilePart`s persist in conversation history with their metadata.
await ( imageData ? onSubmit( message, { imageUrls: imageData } ) : onSubmit( message ) );
} catch {
// A rejected dispatch already surfaces via agenttic's error state;
// put the message back (unless a newer draft replaced it) for a retry.
submitDispatchedRef.current = false;
setInputValue( ( currentValue ) => ( currentValue === '' ? message : currentValue ) );
return;
}
consumeNextMessageExternalContextEntries();
if ( isReaderChat ) {
markSessionUsed( agentConfig?.agentId );
}
},
[
agentConfig?.agentId,
inputValue,
isReaderChat,
isUploadingImages,
onSubmit,
pendingImages.length,
setChatInput,
siteKey,
uploadImagesToWordPress,
]
);
const handleAbort = useCallback( () => {
// `abortUpload` reports whether it stopped an in-flight batch, so a stop
// that lands just after the upload settles still aborts the agent request.
if ( imageUpload?.abortUpload?.() ) {
return;
}
abortCurrentRequest();
}, [ abortCurrentRequest, imageUpload ] );
const submitChatMessage = useCallback(
async ( message?: string ) => {
const submittedMessage = typeof message === 'string' ? message : inputValue;
if ( ! submittedMessage.trim() ) {
return;
}
await onSubmitWithImages( submittedMessage );
// Clear only a dispatched message — an aborted or failed send keeps
// the composer intact, and the user may have typed a new draft.
if ( submitDispatchedRef.current ) {
setInputValue( ( currentValue ) =>
currentValue === submittedMessage ? '' : currentValue
);
}
},
[ inputValue, onSubmitWithImages ]
);
useRegisterCustomActions( { setChatInput, submitChatMessage } );
const handleContextCardAction = useCallback(
( card: ExternalContextCard, action: ExternalContextCardAction ) => {
if ( ! action.prompt ) {
return;
}
// Remove the card immediately so the user gets instant collapse feedback.
// For 'submit' actions the linked context entry stays until the request
// is sent — `consumeNextMessageExternalContextEntries` runs after the
// awaited submit and clears it then.
removeExternalContextCard( card.id );
if ( action.type === 'submit' ) {
void submitChatMessage( action.prompt );
return;
}
setChatInput( action.prompt );
},
[ setChatInput, submitChatMessage ]
);
const dismissContextCard = useCallback( ( card: ExternalContextCard ) => {
removeExternalContextCard( card.id );
card.contextEntryIds?.forEach( ( entryId ) => {
removeExternalContextEntry( entryId );
} );
}, [] );
// Handle navigation continuation if hook is provided
// This allows to resume conversations after full page navigation
useNavigationContinuation?.( {
isProcessing,
sendToolResult: async ( params ) => {
await onSubmit( params.message, {
type: 'tool_result',
toolCallId: params.toolCallId,
toolId: params.toolId,
sessionId: params.sessionId,
} );
},
sessionId: getActiveSessionId(),
pathname: window.location.pathname,
} );
// Listen for inline suggestion clicks dispatched by external providers or the Agenttic bridge below.
useEffect( () => {
const handleInlineSuggestionClick = ( event: Event ) => {
const { value, autoSubmit } = ( event as CustomEvent ).detail;
// Auto-submit suggestions are already sent and the input cleared by the
// AgentUI; repopulating it here would leave the prompt stuck in the composer.
if ( value && ! autoSubmit ) {
const inputValue = value.endsWith( ' ' ) ? value : `${ value } `;
setInputValue( inputValue );
// Focus the textarea and set cursor position to end
const textarea = document.querySelector< HTMLTextAreaElement >(
'.agenttic .Textarea-module_textarea'
);
if ( textarea ) {
textarea.focus();
textarea.setSelectionRange( inputValue.length, inputValue.length );
}
}
};
window.addEventListener( 'big-sky-inline-suggestion-click', handleInlineSuggestionClick );
return () => {
window.removeEventListener( 'big-sky-inline-suggestion-click', handleInlineSuggestionClick );
};
}, [] );
const handleSuggestionClick = useCallback(
( suggestion: Suggestion | string, availableSuggestions?: Suggestion[] ) => {
const value =
typeof suggestion === 'string' ? suggestion : suggestion.prompt ?? suggestion.label;
const autoSubmit = typeof suggestion !== 'string' && !! suggestion.autoSubmit;
const suggestionId = typeof suggestion !== 'string' ? suggestion.id : undefined;
const optionId =
typeof suggestion !== 'string'
? getSelectedOptionId( suggestion, availableSuggestions ?? [] )
: undefined;
const blockType =
typeof suggestion !== 'string' && contextualSuggestionIds.has( suggestion.id )
? selectedBlockType
: undefined;
if ( typeof suggestion !== 'string' ) {
recordBigSkyTracksEvent( 'chat_suggestion_click', {
suggestion_text: suggestion.prompt || '',
suggestion_id: suggestion.id || '',
available_suggestions: formatSuggestionIds( availableSuggestions ?? [] ),
...( optionId ? { option_id: optionId } : {} ),
...( blockType ? { block_type: blockType } : {} ),
} );
}
// Always dispatch so click listeners (e.g. the Jetpack sidebar hiding the
// clicked chip) still fire. `autoSubmit` tells the input listener to skip
// repopulating the composer, which the AgentUI already submitted and cleared.
window.dispatchEvent(
new CustomEvent( 'big-sky-inline-suggestion-click', {
detail: {
value,
autoSubmit,
...( suggestionId ? { suggestionId } : {} ),
},
} )
);
},
[ contextualSuggestionIds, selectedBlockType ]
);
// Invoke abilities setup hook to register hook-based abilities that utilize React context.
// Provides custom action handlers for agent and chat interaction within Big Sky's AI store.
// The hook is stable as `OrchestratorChat` only renders after external providers have been loaded.
useAbilitiesSetup?.( {
addMessage: ( message: BigSkyMessage ) => {
// Transform Big Sky message format to `UIMessage` format and add to chat.
addMessage( convertBigSkyMessageToUIMessage( message ) );
},
clearMessages: () => loadMessages( [] ),
clearSuggestions,
getAgentManager,
isProcessing,
setIsThinking,
deleteMarkedMessages: ( msgs ) => {
const deleteDecisions = msgs.map( ( msg ) => {
const messageFromRequest = msg as Pick< UIMessage, 'id' > &
Partial< Pick< UIMessage, 'content' > >;
const fullMessage = messageFromRequest.content
? ( messageFromRequest as UIMessage )
: messagesRef.current.find( ( message ) => message.id === msg.id );
const isShowComponent = !! fullMessage && isShowComponentMessage( fullMessage );
return {
id: msg.id,
foundMessage: !! fullMessage,
isShowComponent,
tool: fullMessage ? getToolMessageData( fullMessage ) : undefined,
shouldDelete: fullMessage ? ! isShowComponent : false,
};
} );
const deletableMessages = msgs.filter(
( msg ) => deleteDecisions.find( ( decision ) => decision.id === msg.id )?.shouldDelete
);
if ( deletableMessages.length === 0 ) {
return;
}
setDeletedMessageIds(
( prevIds ) => new Set( [ ...prevIds, ...deletableMessages.map( ( msg ) => msg.id ) ] )
);
},
// This ensures the same session ID is used between Big Sky and Calypso agents,
// so that messages will be stored in the same conversation.
getSessionId: getActiveSessionId,
setIsBuildingSite,
setThinkingMessage,
} );
const displayedMessages = useMemo< AgentsManagerUIMessage[] >( () => {
let currentMessages: AgentsManagerUIMessage[] = messages;
currentMessages = currentMessages.filter(
( message ) =>
! deletedMessageIds.has( message.id ) &&
! message.content?.some( ( content ) => content?.text === LOCAL_TOOL_RUNNING_MESSAGE )
);
currentMessages.filter( isShowComponentMessage ).forEach( getShowComponentOrder );
const currentShowComponentIdentities = new Set(
currentMessages
.filter( isShowComponentMessage )
.map( getShowComponentIdentity )
.filter( Boolean )
);
const retainedMessagesToDisplay = [ ...retainedShowComponentMessages.values() ].filter(
( message ) => {
const identity = getShowComponentIdentity( message );
return !! identity && ! currentShowComponentIdentities.has( identity );
}
);
if ( retainedMessagesToDisplay.length > 0 ) {
retainedMessagesToDisplay.forEach( getShowComponentOrder );
currentMessages = [ ...currentMessages, ...retainedMessagesToDisplay ].sort(
( messageA, messageB ) => {
const orderA = getShowComponentOrder( messageA );
const orderB = getShowComponentOrder( messageB );
if ( orderA !== undefined && orderB !== undefined && orderA !== orderB ) {
return orderA - orderB;
}
return ( messageA.timestamp ?? 0 ) - ( messageB.timestamp ?? 0 );
}
);
}
const checkpointActionsByMessageId = new Map(
currentMessages.map( ( message ) => [
message.id,
getCheckpointActionsForMessage( message ),
] )
);
// Group site-build messages only when needed
const hasBuildMessages = siteBuildUtils?.hasSiteBuildMessages( currentMessages );
// Show progress card during styling phase (after structure, dock is visible)
if ( siteBuildUtils?.groupSiteBuildMessages && ( isBuildingSite || hasBuildMessages ) ) {
// Show spinner during post-layout workflow (colors, fonts, images)
currentMessages = siteBuildUtils.groupSiteBuildMessages(
currentMessages,
isBuildingSite ? thinkingMessage : null
);
}
currentMessages = convertToolMessagesToComponents( {
messages: currentMessages,
getChatComponent,
currentPostId,
} );
const latestAgentMessageId = getLatestAgentMessageId( currentMessages );
currentMessages = currentMessages.map( ( message ) => {
const traceId = getTraceIdForMessage( message.id );
const messageWithTraceId = traceId ? { ...message, traceId } : message;
if ( message.id.endsWith( '-next-step' ) ) {
return messageWithTraceId;
}
const directActions = [
...( checkpointActionsByMessageId.get( message.id ) ?? [] ),
...getFeedbackActionsForMessage( message ),
...getCopyActionsForMessage( message ),
...getRegenerateActionsForMessage( message, {
isLatestAgentMessage: message.id === latestAgentMessageId,
isStreaming: isProcessing,
} ),
];
const hasRegisteredCheckpointAction = message.actions?.some(
( action ) => action.id === 'checkpoint'
);
if ( directActions.length === 0 && ! hasRegisteredCheckpointAction ) {
return messageWithTraceId;
}
const existingActions = message.actions?.filter(
( action ) =>
action.id !== 'checkpoint' &&
! action.id.startsWith( 'feedback-' ) &&
action.id !== 'copy' &&
action.id !== 'regenerate'
);
return {
...messageWithTraceId,
actions: [ ...( existingActions ?? [] ), ...directActions ].sort(
( actionA, actionB ) => ( actionA.order ?? Infinity ) - ( actionB.order ?? Infinity )
),
};
} );
return currentMessages;
}, [
currentPostId,
deletedMessageIds,
getChatComponent,
getCopyActionsForMessage,
getCheckpointActionsForMessage,
getShowComponentOrder,
getFeedbackActionsForMessage,
getTraceIdForMessage,
getRegenerateActionsForMessage,
isBuildingSite,
isProcessing,
messages,
retainedShowComponentMessages,
siteBuildUtils,
thinkingMessage,
] );
// Notify parent when has-messages state changes.
const messageCount = displayedMessages.length;
const hasMessages = messageCount > 0;
useEffect( () => {
onHasMessagesChange( hasMessages );
}, [ hasMessages, onHasMessagesChange ] );
// Broadcast conversation activity so other bundles can re-sync transcript cards.
useBroadcastConversationActivity( messageCount );
const latestDisplayedMessage = displayedMessages[ displayedMessages.length - 1 ];
const shouldSuppressTransientThinking = Boolean(
latestDisplayedMessage?.role === 'agent' && latestDisplayedMessage.suppressThinking
);
const showProcessingIndicator =
( isProcessing || ( isThinking && ! isBuildingSite ) ) && ! shouldSuppressTransientThinking;
// Determine which suggestions to show following Big Sky's logic:
// - Empty chat: show provider empty-view chips plus dynamic chips.
// - Active chat/input: show dynamic suggestions only.
let displayedEmptyViewSuggestions: Suggestion[] = [];
if ( ! suggestionsVisible ) {
// Minimized/collapsed: the chat renders no suggestions, so leave the list
// empty to avoid firing chat_suggestions_rendered for hidden chips.
displayedEmptyViewSuggestions = [];
} else if (
! isLoadingConversation &&
displayedMessages.length === 0 &&
inputValue.length === 0
) {
// Prefer the registered store, but fall back to the live `useSuggestions`
// output when the store is empty. Clicking a suggestion calls
// `clearSuggestions()`, which empties the store, and the re-registration
// effect is keyed on the (unchanged) hook output so it won't restore it.
// Persistent empty-view chips must survive that clear.
displayedEmptyViewSuggestions = mergeEmptyViewSuggestions(
emptyViewSuggestions,
replaceEmptyViewSuggestions || suggestions.length === 0
? dynamicSuggestionsList
: suggestions,
replaceEmptyViewSuggestions
);
} else if ( suggestions.length > 0 ) {
displayedEmptyViewSuggestions = suggestions;
}
// Track when a set of suggestions is rendered — the dynamic block-context
// suggestions or, on an empty chat, the empty-view starter chips. Mirrors
// Big Sky, which tracked the empty view too. Dedupe on the rendered ids so
// re-renders with the same set don't re-fire; a set that empties and returns
// to the same content isn't re-tracked.
const displayedSuggestionIds = displayedEmptyViewSuggestions.map( ( s ) => s.id ).join( '|' );
const lastTrackedSuggestionsRef = useRef< string | null >( null );
useEffect( () => {
if ( displayedEmptyViewSuggestions.length === 0 ) {
return;
}
if ( lastTrackedSuggestionsRef.current !== displayedSuggestionIds ) {
recordBigSkyTracksEvent( 'chat_suggestions_rendered', {
suggestions: formatSuggestionIds( displayedEmptyViewSuggestions ),
} );
lastTrackedSuggestionsRef.current = displayedSuggestionIds;
}