@copilotkit/react-core 2.0.0-rc.14 → 2.0.0-rc.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
 
3
- import { A as ExpressionError, B as renderSlot, C as issueKey, D as getMarkdownSurfaceSource, E as containsDynamicValue, F as toJsonSchema, G as CopilotIcon, H as CopilotChatConfigurationProvider, I as defineToolCallRenderer, J as StreamingMarkdownDefaultRenderer, L as MarkdownRendererProvider, M as catalogIdsOf, N as componentCatalogIds, R as useMarkdownRenderer, S as isAsyncIssue, T as withoutRejectedNulls, U as useCopilotChatConfiguration, V as ControlledModalOpenScope, W as useShallowStableRef, a as GenerativeUIToolCallRenderer, i as GenerativeUIChatSlotContext, j as GenerativeUIError, k as BASIC_FUNCTIONS, o as createGenerativeUIActivityRenderer, q as cn, s as createGenerativeUIFunctionCallActivityRenderer, t as MarkdownSurfaces, v as GenerativeUIRuntimeContext, w as validateSchemaSync, x as formatIssues, y as useGenerativeUIRuntime, z as isReactComponentType } from "./MarkdownSurfaces-DKC9Eg_a.mjs";
3
+ import { A as ExpressionError, B as renderSlot, C as issueKey, D as getMarkdownSurfaceSource, E as containsDynamicValue, F as toJsonSchema, G as CopilotIcon, H as CopilotChatConfigurationProvider, I as defineToolCallRenderer, J as StreamingMarkdownDefaultRenderer, L as MarkdownRendererProvider, M as catalogIdsOf, N as componentCatalogIds, R as useMarkdownRenderer, S as isAsyncIssue, T as withoutRejectedNulls, U as useCopilotChatConfiguration, V as ControlledModalOpenScope, W as useShallowStableRef, a as GenerativeUIToolCallRenderer, i as GenerativeUIChatSlotContext, j as GenerativeUIError, k as BASIC_FUNCTIONS, o as createGenerativeUIActivityRenderer, q as cn, s as createGenerativeUIFunctionCallActivityRenderer, t as MarkdownSurfaces, v as GenerativeUIRuntimeContext, w as validateSchemaSync, x as formatIssues, y as useGenerativeUIRuntime, z as isReactComponentType } from "./MarkdownSurfaces-DAEqIF5v.mjs";
4
4
  import { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotChatDefaultLabels, CopilotChatDefaultLabels as CopilotChatDefaultLabels$1, CopilotKitCore, CopilotKitCore as CopilotKitCore$1, CopilotKitCoreErrorCode, CopilotKitCoreErrorCode as CopilotKitCoreErrorCode$1, CopilotKitCoreRuntimeConnectionStatus, CopilotKitCoreRuntimeConnectionStatus as CopilotKitCoreRuntimeConnectionStatus$1, CopilotKitHeaderResolutionError, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL as DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL$1, GENERATE_SANDBOXED_UI_TOOL_NAME, GENERATE_SANDBOXED_UI_TOOL_NAME as GENERATE_SANDBOXED_UI_TOOL_NAME$1, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, INTERRUPT_EVENT_NAME, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, OPEN_GENERATIVE_UI_ACTIVITY_TYPE, OPEN_GENERATIVE_UI_ACTIVITY_TYPE as OPEN_GENERATIVE_UI_ACTIVITY_TYPE$1, ProxiedCopilotRuntimeAgent, ProxiedCopilotRuntimeAgent as ProxiedCopilotRuntimeAgent$1, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, ToolCallStatus as ToolCallStatus$1, TranscriptionError, TranscriptionError as TranscriptionError$1, TranscriptionErrorCode, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorActiveThread as emitInspectorActiveThread$1, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, emitInspectorViewThreadResult as emitInspectorViewThreadResult$1, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isInspectorThreadBridgeEnabled as isInspectorThreadBridgeEnabled$1, isRunCompletionAware, isRunCompletionAware as isRunCompletionAware$1, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorStopViewing as onInspectorStopViewing$1, onInspectorViewThread, onInspectorViewThread as onInspectorViewThread$1, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵInterruptState as ɵInterruptState$1, ɵMAX_SOCKET_RETRIES, ɵOpenGenerativeUIController, ɵOpenGenerativeUIController as ɵOpenGenerativeUIController$1, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, ɵclearAgentInterruptState as ɵclearAgentInterruptState$1, ɵcomposerButtonState, ɵcomposerButtonState as ɵcomposerButtonState$1, ɵcopilotIconSvgAttributes, ɵcopilotIcons, ɵcountFailedToolCalls, ɵcountFailedToolCalls as ɵcountFailedToolCalls$1, ɵcreateMemoryStore, ɵcreateThreadSelectors, ɵcreateThreadStore, ɵcreateThreadStore as ɵcreateThreadStore$1, ɵdeduplicateMessages, ɵdeduplicateMessages as ɵdeduplicateMessages$1, ɵextractCompleteStyles, ɵformatCountLabel, ɵformatCountLabel as ɵformatCountLabel$1, ɵformatLabel, ɵformatLabel as ɵformatLabel$1, ɵformatReasoningDuration, ɵformatReasoningDuration as ɵformatReasoningDuration$1, ɵformatToolNames, ɵformatToolNames as ɵformatToolNames$1, ɵformatWorkDuration, ɵformatWorkDuration as ɵformatWorkDuration$1, ɵgetAgentInterruptState, ɵgetAgentInterruptState as ɵgetAgentInterruptState$1, ɵgetArgumentPreview, ɵgetArgumentPreview as ɵgetArgumentPreview$1, ɵgetLatestTurnKey, ɵgetLatestTurnKey as ɵgetLatestTurnKey$1, ɵgetToolCallLayouts, ɵgetToolCallLayouts as ɵgetToolCallLayouts$1, ɵgetToolCallPreview, ɵgetToolCallPreview as ɵgetToolCallPreview$1, ɵgetToolCallRendererNames, ɵgetToolCallRendererNames as ɵgetToolCallRendererNames$1, ɵgetToolCallRowStatus, ɵgetToolCallRowStatus as ɵgetToolCallRowStatus$1, ɵgetToolResults, ɵgetTurnWork, ɵgetTurnWork as ɵgetTurnWork$1, ɵgetWorkOpenState, ɵgetWorkOpenState as ɵgetWorkOpenState$1, ɵisCopilotKitFeature, ɵisHttpAgent, ɵisHttpAgent as ɵisHttpAgent$1, ɵisRetryableMemoryStatus, ɵisTurnWorkOpen, ɵisTurnWorkOpen as ɵisTurnWorkOpen$1, ɵisTurnWorking, ɵisTurnWorking as ɵisTurnWorking$1, ɵjoinPhoenixChannel$, ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵmessagesFingerprint as ɵmessagesFingerprint$1, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵpluralize, ɵprocessPartialHtml, ɵrecordWorkTime, ɵrecordWorkTime as ɵrecordWorkTime$1, ɵresolveActivityRenderer, ɵresolveActivityRenderer as ɵresolveActivityRenderer$1, ɵresolveComposerKey, ɵresolveComposerKey as ɵresolveComposerKey$1, ɵresolveCustomMessageRenderers, ɵresolveCustomMessageRenderers as ɵresolveCustomMessageRenderers$1, ɵresolveLicenseState, ɵresolveLicenseState as ɵresolveLicenseState$1, ɵresolveThreadsLicense, ɵresolveToolCallRenderer, ɵresolveToolCallRenderer as ɵresolveToolCallRenderer$1, ɵselectFetchMoreError, ɵselectFetchMoreError as ɵselectFetchMoreError$1, ɵselectHasNextPage, ɵselectHasNextPage as ɵselectHasNextPage$1, ɵselectIsFetchingNextPage, ɵselectIsFetchingNextPage as ɵselectIsFetchingNextPage$1, ɵselectIsMutating, ɵselectIsMutating as ɵselectIsMutating$1, ɵselectMemories, ɵselectMemories as ɵselectMemories$1, ɵselectMemoriesAvailable, ɵselectMemoriesAvailable as ɵselectMemoriesAvailable$1, ɵselectMemoriesError, ɵselectMemoriesError as ɵselectMemoriesError$1, ɵselectMemoriesIsLoading, ɵselectMemoriesIsLoading as ɵselectMemoriesIsLoading$1, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectMemoriesRealtimeStatus as ɵselectMemoriesRealtimeStatus$1, ɵselectThreads, ɵselectThreads as ɵselectThreads$1, ɵselectThreadsError, ɵselectThreadsError as ɵselectThreadsError$1, ɵselectThreadsIsLoading, ɵselectThreadsIsLoading as ɵselectThreadsIsLoading$1, ɵstringifyToolCallPayload, ɵstringifyToolCallPayload as ɵstringifyToolCallPayload$1, ɵthreadAdapterEvents, ɵtranscribeAudio, ɵtranscribeAudio as ɵtranscribeAudio$1, ɵtranscriptionErrorMessageKey, ɵtranscriptionErrorMessageKey as ɵtranscriptionErrorMessageKey$1, ɵwithHeaderDefaults, ɵwithHeaderDefaults as ɵwithHeaderDefaults$1 } from "@copilotkit/core";
5
5
  import { ACTIVITY_HISTORY_METADATA, AGUIConnectNotImplementedError, AGUIError, AGUI_METADATA_KEY, AbstractAgent, BackwardCompatibility_0_0_39, BackwardCompatibility_0_0_45, BackwardCompatibility_0_0_57, CompatibilityBoundary, DebugLogger, EventType, FilterToolCallsMiddleware, FunctionMiddleware, HttpAgent, Middleware, PROTOCOL_VERSION, aggregateTokenUsage, authoritativeActivityTypes, buildResumeArray, compactEvents, contentHasMedia, contentToText, convertToLegacyEvents, createDebugLogger, defaultApplyEvents, enforceEvents, enforceOutgoingInput, getRunOutcome, isInterruptExpired, isRecognizedEvent, mergeMetadata, omitOptionalNulls, parseProtoStream, parseSSEStream, randomUUID, randomUUID as randomUUID$1, resolveAgentDebugConfig, resolveDebugLogger, runHttpRequest, structuredClone_, tokenUsageFromAiSdkUsage, tokenUsageFromLangChainMetadata, transformChunks, transformHttpEventStream, verifyEvents, withAuthoritativeActivityTypes } from "@ag-ui/client";
6
6
  import { ActivityDeltaEventSchema, ActivityMessageSchema, ActivitySnapshotEventSchema, AddOperationSchema, AgentCapabilitiesSchema, AssistantMessageSchema, AttributableSchema, AudioInputContentSchema, AudioInputPartSchema, AudioPartSchema, BaseEventSchema, BaseMessageSchema, ContentPartSchema, ContextSchema, CopyOperationSchema, CustomEventSchema, DataSourceSchema, DeveloperMessageSchema, DocumentInputContentSchema, DocumentInputPartSchema, DocumentPartSchema, EventSchema, EventSchemas, EventTypeSchema, ExecutionCapabilitiesSchema, FileSourceSchema, FunctionCallSchema, HumanInTheLoopCapabilitiesSchema, IdentityCapabilitiesSchema, ImageInputContentSchema, ImageInputPartSchema, ImagePartSchema, InputContentDataSourceSchema, InputContentSchema, InputContentSourceSchema, InputContentUrlSourceSchema, InterruptSchema, JsonPatchOperationSchema, JsonPatchSchema, JsonPointerSchema, MessageSchema, MessagesSnapshotEventSchema, MetadataSchema, MoveOperationSchema, MultiAgentCapabilitiesSchema, MultimodalCapabilitiesSchema, MultimodalInputCapabilitiesSchema, MultimodalOutputCapabilitiesSchema, OptionalMetadataSchema, OutputCapabilitiesSchema, PartSourceSchema, RawEventSchema, ReasoningCapabilitiesSchema, ReasoningEncryptedValueEventSchema, ReasoningEncryptedValueSubtypeSchema, ReasoningEndEventSchema, ReasoningMessageChunkEventSchema, ReasoningMessageContentEventSchema, ReasoningMessageEndEventSchema, ReasoningMessageSchema, ReasoningMessageStartEventSchema, ReasoningStartEventSchema, RemoveOperationSchema, ReplaceOperationSchema, ResumeEntrySchema, RoleSchema, RunAgentInputSchema, RunErrorEventSchema, RunFinishedCancelledOutcomeSchema, RunFinishedEventSchema, RunFinishedInterruptOutcomeSchema, RunFinishedOutcomeSchema, RunFinishedSuccessOutcomeSchema, RunStartedEventSchema, StateCapabilitiesSchema, StateDeltaEventSchema, StateSchema, StateSnapshotEventSchema, StepFinishedEventSchema, StepStartedEventSchema, SubagentErrorEventSchema, SubagentFinishedEventSchema, SubagentFinishedOutcomeSchema, SubagentFinishedSuccessOutcomeSchema, SubagentFinishedSuspendedOutcomeSchema, SubagentInfoSchema, SubagentRunIdSchema, SubagentStartedEventSchema, SystemMessageSchema, TestOperationSchema, TextInputContentSchema, TextMessageChunkEventSchema, TextMessageContentEventSchema, TextMessageEndEventSchema, TextMessageRoleSchema, TextMessageStartEventSchema, TextPartSchema, TokenUsageSchema, ToolCallArgsEventSchema, ToolCallChunkEventSchema, ToolCallEndEventSchema, ToolCallResultEventSchema, ToolCallSchema, ToolCallStartEventSchema, ToolMessageSchema, ToolSchema, ToolsCapabilitiesSchema, TransportCapabilitiesSchema, UrlSourceSchema, UserMessageSchema, VideoInputContentSchema, VideoInputPartSchema, VideoPartSchema } from "@ag-ui/core/schemas";
@@ -1237,7 +1237,7 @@ function useRenderToolCall() {
1237
1237
 
1238
1238
  //#endregion
1239
1239
  //#region package.json
1240
- var version$1 = "2.0.0-rc.14";
1240
+ var version$1 = "2.0.0-rc.16";
1241
1241
 
1242
1242
  //#endregion
1243
1243
  //#region src/components/CopilotKitInspector.tsx
@@ -2802,7 +2802,7 @@ function buildGenerativeUIManifest(runtime, threadId) {
2802
2802
  * includeCatalog: true,
2803
2803
  * contextSent: false,
2804
2804
  * });
2805
- * envelope["v1.0"].supportedCatalogIds; // [runtime.ui.id]
2805
+ * envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
2806
2806
  * ```
2807
2807
  */
2808
2808
  function buildGenerativeUIEnvelope(runtime, threadId, options) {
@@ -2811,7 +2811,7 @@ function buildGenerativeUIEnvelope(runtime, threadId, options) {
2811
2811
  const instructions = options.instructions ?? (transport === "markdown" ? buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest)) : void 0);
2812
2812
  const omitComponents = transport === "markdown" && !includeCatalog;
2813
2813
  return {
2814
- "v1.0": {
2814
+ "1.0": {
2815
2815
  supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
2816
2816
  inlineCatalogs: [{
2817
2817
  catalogId: manifest.catalogId,
@@ -3085,13 +3085,16 @@ function createGenerativeUIDispatcher(options) {
3085
3085
  * gesture runs only from an event binding.
3086
3086
  */
3087
3087
  const invokeBasic = (name, args, origin) => {
3088
- const refused = callerError(name, GENERATIVE_UI_FUNCTIONS[name], origin);
3088
+ const info = GENERATIVE_UI_FUNCTIONS[name];
3089
+ const run = BASIC_FUNCTIONS[name];
3090
+ if (info === void 0 || run === void 0) throw new Error(`"${name}" is not a basic function`);
3091
+ const refused = callerError(name, info, origin);
3089
3092
  if (refused) return failWith(name, origin, refused);
3090
3093
  if (args !== void 0 && !(typeof args === "object" && args !== null && !Array.isArray(args))) return failWith(name, origin, new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": args must be an object`));
3091
3094
  try {
3092
3095
  return {
3093
3096
  ok: true,
3094
- result: BASIC_FUNCTIONS[name](args ?? {})
3097
+ result: run(args ?? {})
3095
3098
  };
3096
3099
  } catch (error) {
3097
3100
  return failWith(name, origin, new GenerativeUIError(error instanceof ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
@@ -3265,31 +3268,47 @@ function summarizeRejections(rejections) {
3265
3268
  * with `getState()`.
3266
3269
  */
3267
3270
  var GenerativeUISurfaceManager = class {
3271
+ surfaces = /* @__PURE__ */ new Map();
3272
+ bookkeeping = /* @__PURE__ */ new Map();
3273
+ listeners = /* @__PURE__ */ new Set();
3274
+ /** Mounts of each target id, in mount order. */
3275
+ targets = /* @__PURE__ */ new Map();
3276
+ state = {};
3277
+ /**
3278
+ * User-owned data model values, by surface key, then by path. Kept when a
3279
+ * surface is rebuilt. Cleared when the surface is deleted.
3280
+ */
3281
+ owned = /* @__PURE__ */ new Map();
3282
+ /**
3283
+ * Keys of the surfaces that a `deleteSurface` removed. A surface id is
3284
+ * unique for the life of the page, so a key stays here when its surface is
3285
+ * built again.
3286
+ */
3287
+ deletedKeys = /* @__PURE__ */ new Set();
3288
+ /**
3289
+ * Surfaces that share their data model, by surface key: the parts of a
3290
+ * chat surface that the prose lift split. A user write to one part goes
3291
+ * to every part, so an input in one part drives a binding in another.
3292
+ */
3293
+ linked = /* @__PURE__ */ new Map();
3294
+ webCoreCatalog;
3295
+ activeThreadId;
3296
+ version = 0;
3268
3297
  constructor(ui, options = {}) {
3269
3298
  this.ui = ui;
3270
3299
  this.options = options;
3271
- this.surfaces = /* @__PURE__ */ new Map();
3272
- this.bookkeeping = /* @__PURE__ */ new Map();
3273
- this.listeners = /* @__PURE__ */ new Set();
3274
- this.targets = /* @__PURE__ */ new Map();
3275
- this.state = {};
3276
- this.owned = /* @__PURE__ */ new Map();
3277
- this.deletedKeys = /* @__PURE__ */ new Set();
3278
- this.linked = /* @__PURE__ */ new Map();
3279
- this.version = 0;
3280
- this.subscribe = (listener) => {
3281
- this.listeners.add(listener);
3282
- return () => {
3283
- this.listeners.delete(listener);
3284
- };
3285
- };
3286
- this.getVersion = () => this.version;
3287
- this.getState = () => this.state;
3288
3300
  this.webCoreCatalog = new Catalog$1(ui.id, [...ui.components.keys()].map((name) => ({
3289
3301
  name,
3290
3302
  schema: z.any()
3291
3303
  })), []);
3292
3304
  }
3305
+ subscribe = (listener) => {
3306
+ this.listeners.add(listener);
3307
+ return () => {
3308
+ this.listeners.delete(listener);
3309
+ };
3310
+ };
3311
+ getVersion = () => this.version;
3293
3312
  notify() {
3294
3313
  this.version++;
3295
3314
  for (const listener of [...this.listeners]) listener();
@@ -3475,6 +3494,11 @@ var GenerativeUISurfaceManager = class {
3475
3494
  names: new Set(components)
3476
3495
  };
3477
3496
  }
3497
+ /**
3498
+ * The app state object. It is the same object until a key changes, so it
3499
+ * can be a `useSyncExternalStore` snapshot.
3500
+ */
3501
+ getState = () => this.state;
3478
3502
  /** Sets one state key. Notifies only when the value changed. */
3479
3503
  setState(key, value) {
3480
3504
  if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
@@ -4295,17 +4319,17 @@ function waitForReactCommit() {
4295
4319
  return new Promise((resolve) => setTimeout(resolve, 0));
4296
4320
  }
4297
4321
  var CopilotKitCoreReact = class extends CopilotKitCore$1 {
4322
+ _renderToolCalls = [];
4323
+ _hookRenderToolCalls = /* @__PURE__ */ new Map();
4324
+ _cachedMergedRenderToolCalls = null;
4325
+ _renderCustomMessages = [];
4326
+ _renderActivityMessages = [];
4327
+ _interruptElement = null;
4298
4328
  constructor(config) {
4299
4329
  super({
4300
4330
  ...config,
4301
4331
  ɵwaitForFrameworkUpdates: waitForReactCommit
4302
4332
  });
4303
- this._renderToolCalls = [];
4304
- this._hookRenderToolCalls = /* @__PURE__ */ new Map();
4305
- this._cachedMergedRenderToolCalls = null;
4306
- this._renderCustomMessages = [];
4307
- this._renderActivityMessages = [];
4308
- this._interruptElement = null;
4309
4333
  this._renderToolCalls = config.renderToolCalls ?? [];
4310
4334
  this._renderCustomMessages = config.renderCustomMessages ?? [];
4311
4335
  this._renderActivityMessages = config.renderActivityMessages ?? [];
@@ -6790,7 +6814,7 @@ function useInterrupt(config) {
6790
6814
  try {
6791
6815
  maybePromise = handler({
6792
6816
  event: legacyEvent,
6793
- interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
6817
+ interrupt: pending.kind === "standard" ? pending.interrupts[0] ?? null : null,
6794
6818
  interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
6795
6819
  resolve: resolveRef.current,
6796
6820
  cancel: cancelRef.current
@@ -6819,7 +6843,7 @@ function useInterrupt(config) {
6819
6843
  if (!isEnabled(legacyEvent)) return null;
6820
6844
  return renderRef.current({
6821
6845
  event: legacyEvent,
6822
- interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
6846
+ interrupt: pending.kind === "standard" ? pending.interrupts[0] ?? null : null,
6823
6847
  interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
6824
6848
  result: handlerResult,
6825
6849
  resolve,
@@ -10780,6 +10804,7 @@ function usePinToSend({ scrollRef, contentRef, spacerRef, topOffset = 16 }) {
10780
10804
  const lastNonceRef = useRef(-1);
10781
10805
  useEffect(() => {
10782
10806
  if (sendNonce === lastNonceRef.current) return;
10807
+ const previousNonce = lastNonceRef.current;
10783
10808
  lastNonceRef.current = sendNonce;
10784
10809
  if (!id) return;
10785
10810
  const scrollEl = scrollRef.current;
@@ -10795,7 +10820,9 @@ function usePinToSend({ scrollRef, contentRef, spacerRef, topOffset = 16 }) {
10795
10820
  const bubbleHeight = Math.max(0, userMessageHeight - paddingTop);
10796
10821
  const spacerHeight = Math.max(0, viewportHeight - bubbleHeight - topOffset);
10797
10822
  spacerEl.style.height = `${spacerHeight}px`;
10823
+ let pinned = false;
10798
10824
  const raf = requestAnimationFrame(() => {
10825
+ pinned = true;
10799
10826
  const targetTop = computeOffsetTop(targetEl, scrollEl) + paddingTop - topOffset;
10800
10827
  scrollEl.scrollTo({
10801
10828
  top: Math.max(0, targetTop),
@@ -10812,6 +10839,7 @@ function usePinToSend({ scrollRef, contentRef, spacerRef, topOffset = 16 }) {
10812
10839
  return () => {
10813
10840
  cancelAnimationFrame(raf);
10814
10841
  ro.disconnect();
10842
+ if (!pinned) lastNonceRef.current = previousNonce;
10815
10843
  };
10816
10844
  }, [
10817
10845
  id,
@@ -10847,15 +10875,16 @@ function DropOverlay() {
10847
10875
  })
10848
10876
  });
10849
10877
  }
10850
- function CopilotChatView({ messageView, input, scrollView, suggestionView, welcomeScreen, messages = [], autoScroll = true, isRunning = false, suggestions, suggestionLoadingIndexes, onSelectSuggestion, onSubmitMessage, onStop, inputMode, inputValue, onInputChange, onStartTranscribe, onCancelTranscribe, onFinishTranscribe, onFinishTranscribeWithAudio, attachments, onRemoveAttachment, onAddFile, dragOver, onDragOver, onDragLeave, onDrop, isConnecting = false, hasExplicitThreadId = false, intelligenceIndicator, children, className, ...props }) {
10878
+ function CopilotChatView({ messageView, input, scrollView, suggestionView, welcomeScreen, messages = [], autoScroll = true, isRunning = false, suggestions, suggestionLoadingIndexes, onSelectSuggestion, onSubmitMessage, onStop, inputMode, inputValue, onInputChange, onStartTranscribe, onCancelTranscribe, onFinishTranscribe, onFinishTranscribeWithAudio, attachments, onRemoveAttachment, onAddFile, dragOver, onDragOver, onDragLeave, onDrop, isConnecting = false, connectingIndicator, hasExplicitThreadId = false, intelligenceIndicator, children, className, ...props }) {
10851
10879
  const configuredThreadId = useCopilotChatConfiguration()?.threadId;
10852
10880
  const [fallbackThreadId, setFallbackThreadId] = useState(messages[0]?.id);
10853
10881
  const previousMessageIds = useRef(/* @__PURE__ */ new Set());
10854
10882
  useEffect(() => {
10855
- if (messages.length === 0) return;
10883
+ const firstMessage = messages[0];
10884
+ if (firstMessage === void 0) return;
10856
10885
  const overlaps = messages.some((message) => previousMessageIds.current.has(message.id));
10857
10886
  previousMessageIds.current = new Set(messages.map((message) => message.id));
10858
- if (!overlaps) setFallbackThreadId(messages[0].id);
10887
+ if (!overlaps) setFallbackThreadId(firstMessage.id);
10859
10888
  }, [messages]);
10860
10889
  const scrollThreadId = configuredThreadId ?? fallbackThreadId;
10861
10890
  const [inputContainerEl, setInputContainerEl] = useState(null);
@@ -10921,6 +10950,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
10921
10950
  onSelectSuggestion,
10922
10951
  className: "cpk-chat-view-suggestion-view"
10923
10952
  }) : null;
10953
+ const BoundConnectingIndicator = isConnecting && messages.length === 0 && connectingIndicator !== false ? renderSlot(connectingIndicator === true ? void 0 : connectingIndicator, CopilotChatView.ConnectingIndicator, {}) : null;
10924
10954
  const BoundScrollView = renderSlot(scrollView, CopilotChatView.ScrollView, {
10925
10955
  autoScroll,
10926
10956
  scrollThreadId,
@@ -10931,10 +10961,14 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
10931
10961
  style: { paddingBottom: `${inputContainerHeight + (hasSuggestions ? 4 : 32)}px` },
10932
10962
  children: /* @__PURE__ */ jsxs("div", {
10933
10963
  className: "cpk-chat-view-feed",
10934
- children: [BoundMessageView, hasSuggestions ? /* @__PURE__ */ jsx("div", {
10935
- className: "cpk-chat-view-suggestions",
10936
- children: BoundSuggestionView
10937
- }) : null]
10964
+ children: [
10965
+ BoundConnectingIndicator,
10966
+ BoundMessageView,
10967
+ hasSuggestions ? /* @__PURE__ */ jsx("div", {
10968
+ className: "cpk-chat-view-suggestions",
10969
+ children: BoundSuggestionView
10970
+ }) : null
10971
+ ]
10938
10972
  })
10939
10973
  })
10940
10974
  });
@@ -10971,6 +11005,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
10971
11005
  "data-copilotkit": true,
10972
11006
  "data-testid": "copilot-chat",
10973
11007
  "data-copilot-running": isRunning ? "true" : "false",
11008
+ "data-copilot-connecting": isConnecting ? "true" : "false",
10974
11009
  onDragOver,
10975
11010
  onDragLeave,
10976
11011
  onDrop,
@@ -10981,6 +11016,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
10981
11016
  }
10982
11017
  if (children) return /* @__PURE__ */ jsx("div", {
10983
11018
  "data-copilotkit": true,
11019
+ "data-copilot-connecting": isConnecting ? "true" : "false",
10984
11020
  style: { display: "contents" },
10985
11021
  children: children({
10986
11022
  messageView: BoundMessageView,
@@ -10993,6 +11029,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
10993
11029
  "data-copilotkit": true,
10994
11030
  "data-testid": "copilot-chat",
10995
11031
  "data-copilot-running": isRunning ? "true" : "false",
11032
+ "data-copilot-connecting": isConnecting ? "true" : "false",
10996
11033
  onDragOver,
10997
11034
  onDragLeave,
10998
11035
  onDrop,
@@ -11208,13 +11245,15 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11208
11245
  if (mode === "pin-to-bottom") return;
11209
11246
  const scrollElement = nonAutoScrollEl;
11210
11247
  if (!scrollElement) return;
11248
+ const contentElement = contentRef.current;
11211
11249
  const checkScroll = () => {
11212
- setShowScrollButton(!(scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight < 10));
11250
+ setShowScrollButton((contentElement ? contentElement.getBoundingClientRect().bottom - scrollElement.getBoundingClientRect().bottom : scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight) >= 10);
11213
11251
  };
11214
11252
  checkScroll();
11215
11253
  scrollElement.addEventListener("scroll", checkScroll);
11216
11254
  const resizeObserver = new ResizeObserver(checkScroll);
11217
11255
  resizeObserver.observe(scrollElement);
11256
+ if (contentElement) resizeObserver.observe(contentElement);
11218
11257
  return () => {
11219
11258
  scrollElement.removeEventListener("scroll", checkScroll);
11220
11259
  resizeObserver.disconnect();
@@ -11300,6 +11339,22 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11300
11339
  className,
11301
11340
  ...props
11302
11341
  });
11342
+ _CopilotChatView.ConnectingIndicator = ({ className, ...props }) => {
11343
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
11344
+ return /* @__PURE__ */ jsxs("div", {
11345
+ "data-testid": "copilot-connecting-indicator",
11346
+ role: "status",
11347
+ className: cn("cpk-chat-view-connecting-indicator", className),
11348
+ ...props,
11349
+ children: [/* @__PURE__ */ jsx(CopilotIcon, {
11350
+ name: "Loader2",
11351
+ className: "cpk-chat-view-connecting-spinner"
11352
+ }), /* @__PURE__ */ jsx("span", {
11353
+ className: "cpk-chat-view-connecting-label",
11354
+ children: labels.chatConnectingLabel
11355
+ })]
11356
+ });
11357
+ };
11303
11358
  _CopilotChatView.WelcomeMessage = ({ className, ...props }) => {
11304
11359
  const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
11305
11360
  return /* @__PURE__ */ jsx("h1", {
@@ -12028,7 +12083,10 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12028
12083
  const effectiveMode = isTranscribing ? "processing" : transcribeMode;
12029
12084
  const messages = useMemo(() => [...agent.messages], [ɵmessagesFingerprint$1(agent.messages)]);
12030
12085
  const lastUserMessageId = useMemo(() => {
12031
- for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user") return messages[i].id;
12086
+ for (let i = messages.length - 1; i >= 0; i--) {
12087
+ const message = messages[i];
12088
+ if (message?.role === "user") return message.id;
12089
+ }
12032
12090
  return null;
12033
12091
  }, [messages]);
12034
12092
  const [sendNonce, setSendNonce] = useState(0);