@copilotkit/react-core 1.82.0 → 1.84.0

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.
Files changed (46) hide show
  1. package/dist/{MarkdownSurfaces-DGpjmPaB.mjs → MarkdownSurfaces-DV9P0Gi9.mjs} +55 -13
  2. package/dist/MarkdownSurfaces-DV9P0Gi9.mjs.map +1 -0
  3. package/dist/{MarkdownSurfaces-FF5za2kU.cjs → MarkdownSurfaces-IUaWSJ0E.cjs} +54 -12
  4. package/dist/MarkdownSurfaces-IUaWSJ0E.cjs.map +1 -0
  5. package/dist/{copilotkit-CVvbU9lV.cjs → copilotkit-BOTf5RHF.cjs} +296 -291
  6. package/dist/copilotkit-BOTf5RHF.cjs.map +1 -0
  7. package/dist/{copilotkit-wqaNanhw.d.cts → copilotkit-C3mvJexb.d.cts} +31 -8
  8. package/dist/copilotkit-C3mvJexb.d.cts.map +1 -0
  9. package/dist/{copilotkit-DDReN1Px.mjs → copilotkit-CKnD8GeM.mjs} +300 -295
  10. package/dist/copilotkit-CKnD8GeM.mjs.map +1 -0
  11. package/dist/{copilotkit-C765tOUi.d.mts → copilotkit-CnYo662V.d.mts} +31 -8
  12. package/dist/copilotkit-CnYo662V.d.mts.map +1 -0
  13. package/dist/index.cjs +2 -2
  14. package/dist/index.d.cts +1 -1
  15. package/dist/index.d.mts +1 -1
  16. package/dist/index.mjs +2 -2
  17. package/dist/index.umd.js +199 -289
  18. package/dist/index.umd.js.map +1 -1
  19. package/dist/v2/generative-ui.cjs +33 -54
  20. package/dist/v2/generative-ui.cjs.map +1 -1
  21. package/dist/v2/generative-ui.d.cts +118 -118
  22. package/dist/v2/generative-ui.d.mts +118 -118
  23. package/dist/v2/generative-ui.mjs +33 -54
  24. package/dist/v2/generative-ui.mjs.map +1 -1
  25. package/dist/v2/headless.cjs +32 -16
  26. package/dist/v2/headless.cjs.map +1 -1
  27. package/dist/v2/headless.d.cts +2 -0
  28. package/dist/v2/headless.d.cts.map +1 -1
  29. package/dist/v2/headless.d.mts +2 -0
  30. package/dist/v2/headless.d.mts.map +1 -1
  31. package/dist/v2/headless.mjs +33 -17
  32. package/dist/v2/headless.mjs.map +1 -1
  33. package/dist/v2/index.cjs +14 -2
  34. package/dist/v2/index.css +1 -1
  35. package/dist/v2/index.d.cts +2 -2
  36. package/dist/v2/index.d.mts +2 -2
  37. package/dist/v2/index.mjs +3 -3
  38. package/dist/v2/index.umd.js +359 -300
  39. package/dist/v2/index.umd.js.map +1 -1
  40. package/package.json +8 -8
  41. package/dist/MarkdownSurfaces-DGpjmPaB.mjs.map +0 -1
  42. package/dist/MarkdownSurfaces-FF5za2kU.cjs.map +0 -1
  43. package/dist/copilotkit-C765tOUi.d.mts.map +0 -1
  44. package/dist/copilotkit-CVvbU9lV.cjs.map +0 -1
  45. package/dist/copilotkit-DDReN1Px.mjs.map +0 -1
  46. package/dist/copilotkit-wqaNanhw.d.cts.map +0 -1
@@ -1,4 +1,4 @@
1
- const require_MarkdownSurfaces = require('./MarkdownSurfaces-FF5za2kU.cjs');
1
+ const require_MarkdownSurfaces = require('./MarkdownSurfaces-IUaWSJ0E.cjs');
2
2
  let react = require("react");
3
3
  react = require_MarkdownSurfaces.__toESM(react);
4
4
  let _copilotkit_core = require("@copilotkit/core");
@@ -1325,7 +1325,7 @@ function useRenderToolCall() {
1325
1325
 
1326
1326
  //#endregion
1327
1327
  //#region package.json
1328
- var version = "1.82.0";
1328
+ var version = "1.84.0";
1329
1329
 
1330
1330
  //#endregion
1331
1331
  //#region src/v2/components/CopilotKitInspector.tsx
@@ -3074,6 +3074,35 @@ function builtInFunctionManifests() {
3074
3074
  }]));
3075
3075
  }
3076
3076
  /**
3077
+ * The manifest of a catalog, with no React runtime: the components of `ui`,
3078
+ * the built-in functions (minus the names the app declares) and
3079
+ * `options.functions`, the chat target and `options.targets`, and
3080
+ * `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
3081
+ * manifest with it; tools that run outside React use it directly.
3082
+ *
3083
+ * @example
3084
+ * ```ts
3085
+ * const manifest = buildCatalogManifest(standardUI);
3086
+ * manifest.targets; // [{ id: "chat", kind: "chat" }]
3087
+ * ```
3088
+ */
3089
+ function buildCatalogManifest(ui, options = {}) {
3090
+ return {
3091
+ catalogId: ui.id,
3092
+ catalogIds: require_MarkdownSurfaces.catalogIdsOf(ui),
3093
+ components: (0, _copilotkit_shared.applyDescriptionOverrides)({ components: ui.manifestComponents }, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().descriptions).manifest.components,
3094
+ functions: {
3095
+ ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
3096
+ ...options.functions
3097
+ },
3098
+ targets: [{
3099
+ id: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
3100
+ kind: "chat"
3101
+ }, ...options.targets ?? []],
3102
+ surfaces: options.surfaces ?? {}
3103
+ };
3104
+ }
3105
+ /**
3077
3106
  * Builds the per-run manifest. Never contains handlers or renderers.
3078
3107
  *
3079
3108
  * - `functions`: the built-in functions, then the declared functions with
@@ -3088,20 +3117,11 @@ function buildGenerativeUIManifest(runtime, threadId) {
3088
3117
  kind: "inline",
3089
3118
  ...rest
3090
3119
  }));
3091
- return {
3092
- catalogId: ui.id,
3093
- catalogIds: require_MarkdownSurfaces.catalogIdsOf(ui),
3094
- components: ui.manifestComponents,
3095
- functions: {
3096
- ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
3097
- ...dispatcher.listExposed()
3098
- },
3099
- targets: [{
3100
- id: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
3101
- kind: "chat"
3102
- }, ...inlineTargets],
3120
+ return buildCatalogManifest(ui, {
3121
+ functions: dispatcher.listExposed(),
3122
+ targets: inlineTargets,
3103
3123
  surfaces: threadId ? manager.describeSurfaces(threadId) : {}
3104
- };
3124
+ });
3105
3125
  }
3106
3126
  /**
3107
3127
  * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
@@ -3124,7 +3144,7 @@ function buildGenerativeUIManifest(runtime, threadId) {
3124
3144
  * includeCatalog: true,
3125
3145
  * contextSent: false,
3126
3146
  * });
3127
- * envelope["v1.0"].supportedCatalogIds; // [runtime.ui.id]
3147
+ * envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
3128
3148
  * ```
3129
3149
  */
3130
3150
  function buildGenerativeUIEnvelope(runtime, threadId, options) {
@@ -3133,7 +3153,7 @@ function buildGenerativeUIEnvelope(runtime, threadId, options) {
3133
3153
  const instructions = options.instructions ?? (transport === "markdown" ? (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest)) : void 0);
3134
3154
  const omitComponents = transport === "markdown" && !includeCatalog;
3135
3155
  return {
3136
- "v1.0": {
3156
+ "1.0": {
3137
3157
  supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
3138
3158
  inlineCatalogs: [{
3139
3159
  catalogId: manifest.catalogId,
@@ -3154,251 +3174,6 @@ function buildGenerativeUIEnvelope(runtime, threadId, options) {
3154
3174
  };
3155
3175
  }
3156
3176
 
3157
- //#endregion
3158
- //#region src/v2/generative-ui/markdown/context.ts
3159
- /** Objects nested deeper than this show as `object`. */
3160
- const MAX_OBJECT_DEPTH = 2;
3161
- /** A prop must appear verbatim in at least this many components to be hoisted. */
3162
- const COMMON_PROP_MIN_COMPONENTS = 8;
3163
- /** A JSON Schema of a list of schemas (`anyOf`, `oneOf`), else an empty list. */
3164
- function schemaList(value) {
3165
- return Array.isArray(value) ? value.filter(require_MarkdownSurfaces.isRecord) : [];
3166
- }
3167
- /**
3168
- * Puts a top-level union in parentheses, so that `[]` applies to all of
3169
- * it. A union inside braces needs none.
3170
- */
3171
- function asArrayItem(type) {
3172
- let outside = type;
3173
- for (let inner = outside.replace(/\{[^{}]*\}/g, ""); inner !== outside;) {
3174
- outside = inner;
3175
- inner = outside.replace(/\{[^{}]*\}/g, "");
3176
- }
3177
- return outside.includes(" | ") ? `(${type})[]` : `${type}[]`;
3178
- }
3179
- /**
3180
- * A JSON Schema as a short TypeScript-like type, for example
3181
- * `{ label: string; size?: "sm" | "md" }`.
3182
- */
3183
- function compactType(schema, depth) {
3184
- const ref = (0, _copilotkit_shared.childRefKind)(schema);
3185
- if (ref === "single") return "componentId";
3186
- if (ref === "multiple") return "componentId[] | { componentId: string; path: string }";
3187
- if ("const" in schema) return JSON.stringify(schema.const);
3188
- if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
3189
- const variants = [...schemaList(schema.anyOf), ...schemaList(schema.oneOf)];
3190
- if (variants.length > 0) return variants.map((variant) => compactType(variant, depth)).join(" | ");
3191
- return (Array.isArray(schema.type) ? schema.type : [schema.type]).map((type) => {
3192
- switch (type) {
3193
- case "string":
3194
- case "boolean":
3195
- case "null": return type;
3196
- case "number":
3197
- case "integer": return "number";
3198
- case "array": return require_MarkdownSurfaces.isRecord(schema.items) ? asArrayItem(compactType(schema.items, depth)) : "unknown[]";
3199
- case "object": return compactObject(schema, depth);
3200
- default: return "unknown";
3201
- }
3202
- }).join(" | ");
3203
- }
3204
- /** An object schema as `{ key: type; other?: type }`. */
3205
- function compactObject(schema, depth) {
3206
- const properties = require_MarkdownSurfaces.isRecord(schema.properties) ? schema.properties : {};
3207
- const entries = Object.entries(properties);
3208
- if (entries.length === 0) return require_MarkdownSurfaces.isRecord(schema.additionalProperties) ? `Record<string, ${compactType(schema.additionalProperties, depth + 1)}>` : "object";
3209
- if (depth >= MAX_OBJECT_DEPTH) return "object";
3210
- const required = Array.isArray(schema.required) ? schema.required : [];
3211
- return `{ ${entries.map(([key, value]) => {
3212
- const type = require_MarkdownSurfaces.isRecord(value) ? compactType(value, depth + 1) : "unknown";
3213
- return `${key}${required.includes(key) ? "" : "?"}: ${type}`;
3214
- }).join("; ")} }`;
3215
- }
3216
- /** A schema as its type, with its description after `//`. */
3217
- function describedType(schema, depth) {
3218
- const type = compactType(schema, depth);
3219
- return typeof schema.description === "string" ? `${type} // ${schema.description}` : type;
3220
- }
3221
- /** The props of a component: `{ "label": "string", "size?": "..." }`. */
3222
- function compactProps(schema) {
3223
- const properties = require_MarkdownSurfaces.isRecord(schema.properties) ? schema.properties : {};
3224
- const required = Array.isArray(schema.required) ? schema.required : [];
3225
- const props = {};
3226
- for (const [key, value] of Object.entries(properties)) {
3227
- if (!require_MarkdownSurfaces.isRecord(value)) continue;
3228
- const name = required.includes(key) ? key : `${key}?`;
3229
- props[name] = describedType(value, 1);
3230
- }
3231
- return props;
3232
- }
3233
- /**
3234
- * The prop set worth listing once. Candidates are (key, type) pairs that at
3235
- * least {@link COMMON_PROP_MIN_COMPONENTS} components carry verbatim. The
3236
- * candidate subset of each component is a possible common set, scored by
3237
- * the characters it saves (set size times the components that contain all
3238
- * of it). `undefined` when no set is shared by enough components.
3239
- */
3240
- function findCommonProps(propsList) {
3241
- const pairKey = (key, type) => `${key}\u0000${type}`;
3242
- const counts = /* @__PURE__ */ new Map();
3243
- for (const props of propsList) for (const [key, type] of Object.entries(props)) {
3244
- const id = pairKey(key, type);
3245
- counts.set(id, (counts.get(id) ?? 0) + 1);
3246
- }
3247
- let best;
3248
- let bestScore = 0;
3249
- const seen = /* @__PURE__ */ new Set();
3250
- for (const props of propsList) {
3251
- const subset = Object.entries(props).filter(([key, type]) => (counts.get(pairKey(key, type)) ?? 0) >= COMMON_PROP_MIN_COMPONENTS);
3252
- if (subset.length < 2) continue;
3253
- const signature = subset.map(([key, type]) => pairKey(key, type)).join("\n");
3254
- if (seen.has(signature)) continue;
3255
- seen.add(signature);
3256
- const members = propsList.filter((other) => subset.every(([key, type]) => other[key] === type)).length;
3257
- if (members < COMMON_PROP_MIN_COMPONENTS) continue;
3258
- const score = subset.reduce((total, [key, type]) => total + key.length + type.length, 0) * (members - 1);
3259
- if (score > bestScore) {
3260
- bestScore = score;
3261
- best = Object.fromEntries(subset);
3262
- }
3263
- }
3264
- return best;
3265
- }
3266
- /**
3267
- * The component schema of the markdown transport, from the per-run
3268
- * manifest. It is smaller than the manifest: each prop is one short type,
3269
- * and the props that many components share verbatim (the layout props of
3270
- * the containers) are listed once in `commonProps`; a component that takes
3271
- * them is flagged `includesCommonProps`.
3272
- * It has the catalog id, the targets with their descriptions and their
3273
- * component lists, the functions with their parameters, the components
3274
- * with their props, events and slots, and the surfaces of the thread. A surface lists the
3275
- * values that the user set and the operations that the client dropped.
3276
- *
3277
- * @param manifest - The manifest from `buildGenerativeUIManifest`.
3278
- * @returns A JSON-ready object.
3279
- *
3280
- * @example
3281
- * ```ts
3282
- * const value = JSON.stringify(
3283
- * buildCompactGenerativeUISchema(buildGenerativeUIManifest(runtime, threadId)),
3284
- * );
3285
- * ```
3286
- */
3287
- function buildCompactGenerativeUISchema(manifest) {
3288
- const components = {};
3289
- for (const [name, component] of Object.entries(manifest.components)) {
3290
- const events = Object.entries(component.events ?? {}).map(([event, definition]) => [event, definition.description ?? compactType(definition.parameters, 0)]);
3291
- components[name] = {
3292
- ...component.description ? { description: component.description } : {},
3293
- props: compactProps(component.props),
3294
- ...events.length > 0 ? { events: Object.fromEntries(events) } : {},
3295
- ...component.slots ? { slots: component.slots } : {}
3296
- };
3297
- }
3298
- const common = findCommonProps(Object.values(components).map((component) => component.props));
3299
- if (common) {
3300
- const commonKeys = Object.keys(common);
3301
- for (const component of Object.values(components)) {
3302
- if (!commonKeys.every((key) => component.props[key] === common[key])) continue;
3303
- component.includesCommonProps = true;
3304
- component.props = Object.fromEntries(Object.entries(component.props).filter(([key]) => !(key in common)));
3305
- }
3306
- }
3307
- const functions = Object.fromEntries(Object.entries(manifest.functions).map(([name, fn]) => {
3308
- const signature = fn.parameters.description;
3309
- const hasSignature = typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2;
3310
- const callers = (0, _copilotkit_shared.functionCallers)(fn);
3311
- return [name, {
3312
- ...fn.description ? { description: fn.description } : {},
3313
- parameters: hasSignature ? signature : compactType(fn.parameters, 0),
3314
- ...callers.agent && _copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS ? { callers: callers.renderer ? "UI or agent" : "agent only" } : {}
3315
- }];
3316
- }));
3317
- return {
3318
- catalogId: manifest.catalogId,
3319
- targets: manifest.targets,
3320
- functions,
3321
- ...common ? { commonProps: common } : {},
3322
- components,
3323
- surfaces: manifest.surfaces
3324
- };
3325
- }
3326
- /**
3327
- * Registers the two context entries of the markdown transport: the compact
3328
- * component schema and the fence guideline. Both go only to `agentIds`.
3329
- *
3330
- * The schema is built again at each run start and when a
3331
- * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
3332
- * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
3333
- *
3334
- * @param copilotkit - The CopilotKit core of the provider.
3335
- * @param runtime - The generative UI runtime parts, or null without one.
3336
- * @param options - `enabled` and `agentIds`.
3337
- *
3338
- * @example
3339
- * ```ts
3340
- * useGenerativeUIMarkdownContext(copilotkit, core, {
3341
- * enabled: config?.transport === "markdown" && config.sendContext !== false,
3342
- * agentIds: config?.agentIds,
3343
- * });
3344
- * ```
3345
- */
3346
- function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
3347
- const { enabled, agentIds } = options;
3348
- const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
3349
- (0, react.useEffect)(() => {
3350
- if (!runtime || !enabled) return;
3351
- const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
3352
- const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
3353
- let guidelineId;
3354
- let guidelineValue;
3355
- let schemaId;
3356
- let schemaValue;
3357
- const refreshSchema = (threadId) => {
3358
- const manifest = buildGenerativeUIManifest(runtime, threadId);
3359
- const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
3360
- if (guideline !== guidelineValue) {
3361
- if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3362
- guidelineValue = guideline;
3363
- guidelineId = copilotkit.addContext({
3364
- description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
3365
- value: guideline,
3366
- ...scope
3367
- });
3368
- }
3369
- const value = JSON.stringify(buildCompactGenerativeUISchema(manifest));
3370
- if (value === schemaValue) return;
3371
- if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3372
- schemaValue = value;
3373
- schemaId = copilotkit.addContext({
3374
- description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
3375
- value,
3376
- ...scope
3377
- });
3378
- };
3379
- refreshSchema(runtime.manager.getActiveThread());
3380
- let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
3381
- const unsubscribeManager = runtime.manager.subscribe(() => {
3382
- const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
3383
- if (nextKey === targetsKey) return;
3384
- targetsKey = nextKey;
3385
- refreshSchema(runtime.manager.getActiveThread());
3386
- });
3387
- const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
3388
- return () => {
3389
- subscription.unsubscribe();
3390
- unsubscribeManager();
3391
- if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3392
- if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3393
- };
3394
- }, [
3395
- copilotkit,
3396
- runtime,
3397
- enabled,
3398
- agentIdsKey
3399
- ]);
3400
- }
3401
-
3402
3177
  //#endregion
3403
3178
  //#region src/v2/generative-ui/debug-source.ts
3404
3179
  /**
@@ -3431,7 +3206,7 @@ function describeGenerativeUIRun(runtime, threadId, options) {
3431
3206
  }]
3432
3207
  };
3433
3208
  const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
3434
- const schema = JSON.stringify(buildCompactGenerativeUISchema(manifest));
3209
+ const schema = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
3435
3210
  return {
3436
3211
  envelope,
3437
3212
  prompt: [{
@@ -3718,6 +3493,84 @@ function createGenerativeUIDispatcher(options) {
3718
3493
  };
3719
3494
  }
3720
3495
 
3496
+ //#endregion
3497
+ //#region src/v2/generative-ui/markdown/context.ts
3498
+ /**
3499
+ * Registers the two context entries of the markdown transport: the compact
3500
+ * component schema and the fence guideline. Both go only to `agentIds`.
3501
+ *
3502
+ * The schema is built again at each run start and when a
3503
+ * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
3504
+ * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
3505
+ *
3506
+ * @param copilotkit - The CopilotKit core of the provider.
3507
+ * @param runtime - The generative UI runtime parts, or null without one.
3508
+ * @param options - `enabled` and `agentIds`.
3509
+ *
3510
+ * @example
3511
+ * ```ts
3512
+ * useGenerativeUIMarkdownContext(copilotkit, core, {
3513
+ * enabled: config?.transport === "markdown" && config.sendContext !== false,
3514
+ * agentIds: config?.agentIds,
3515
+ * });
3516
+ * ```
3517
+ */
3518
+ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
3519
+ const { enabled, agentIds } = options;
3520
+ const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
3521
+ (0, react.useEffect)(() => {
3522
+ if (!runtime || !enabled) return;
3523
+ const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
3524
+ const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
3525
+ let guidelineId;
3526
+ let guidelineValue;
3527
+ let schemaId;
3528
+ let schemaValue;
3529
+ const refreshSchema = (threadId) => {
3530
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
3531
+ const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
3532
+ if (guideline !== guidelineValue) {
3533
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3534
+ guidelineValue = guideline;
3535
+ guidelineId = copilotkit.addContext({
3536
+ description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
3537
+ value: guideline,
3538
+ ...scope
3539
+ });
3540
+ }
3541
+ const value = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
3542
+ if (value === schemaValue) return;
3543
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3544
+ schemaValue = value;
3545
+ schemaId = copilotkit.addContext({
3546
+ description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
3547
+ value,
3548
+ ...scope
3549
+ });
3550
+ };
3551
+ refreshSchema(runtime.manager.getActiveThread());
3552
+ let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
3553
+ const unsubscribeManager = runtime.manager.subscribe(() => {
3554
+ const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
3555
+ if (nextKey === targetsKey) return;
3556
+ targetsKey = nextKey;
3557
+ refreshSchema(runtime.manager.getActiveThread());
3558
+ });
3559
+ const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
3560
+ return () => {
3561
+ subscription.unsubscribe();
3562
+ unsubscribeManager();
3563
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3564
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3565
+ };
3566
+ }, [
3567
+ copilotkit,
3568
+ runtime,
3569
+ enabled,
3570
+ agentIdsKey
3571
+ ]);
3572
+ }
3573
+
3721
3574
  //#endregion
3722
3575
  //#region src/v2/generative-ui/surface-manager.ts
3723
3576
  function surfaceKey(threadId, surfaceId) {
@@ -7023,6 +6876,7 @@ const INTERRUPT_EVENT_NAME = "on_interrupt";
7023
6876
 
7024
6877
  //#endregion
7025
6878
  //#region src/v2/hooks/use-interrupt.tsx
6879
+ /** Recognize thenables returned by interrupt preprocessing handlers. */
7026
6880
  function isPromiseLike(value) {
7027
6881
  return (typeof value === "object" || typeof value === "function") && value !== null && typeof Reflect.get(value, "then") === "function";
7028
6882
  }
@@ -7073,7 +6927,6 @@ function useInterrupt(config) {
7073
6927
  const [handlerResult, setHandlerResult] = (0, react.useState)(null);
7074
6928
  const interruptStateRef = (0, react.useRef)(new _copilotkit_core.ɵInterruptState());
7075
6929
  (0, react.useEffect)(() => {
7076
- const interruptState = interruptStateRef.current;
7077
6930
  let localLegacy = null;
7078
6931
  let localStandard = null;
7079
6932
  const subscription = agent.subscribe({
@@ -7086,19 +6939,21 @@ function useInterrupt(config) {
7086
6939
  onRunFinishedEvent: (params) => {
7087
6940
  if (params.outcome === "interrupt") localStandard = params.interrupts;
7088
6941
  },
7089
- onRunStartedEvent: () => {
6942
+ onRunStartedEvent: (params) => {
6943
+ if (!agent.pendingInterrupts?.length || params?.input?.resume !== void 0) (0, _copilotkit_core.ɵclearAgentInterruptState)(agent);
7090
6944
  localLegacy = null;
7091
6945
  localStandard = null;
7092
- interruptState.clear();
6946
+ interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
7093
6947
  setPending(null);
7094
6948
  },
7095
6949
  onRunFinalized: () => {
7096
6950
  if (localStandard && localStandard.length > 0) {
7097
- interruptState.setStandard(localStandard);
7098
- setPending(interruptState.pending);
6951
+ interruptStateRef.current = (0, _copilotkit_core.ɵgetAgentInterruptState)(agent, localStandard);
6952
+ setPending(interruptStateRef.current.pending);
7099
6953
  } else if (localLegacy) {
7100
- interruptState.setLegacy(localLegacy);
7101
- setPending(interruptState.pending);
6954
+ interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
6955
+ interruptStateRef.current.setLegacy(localLegacy);
6956
+ setPending(interruptStateRef.current.pending);
7102
6957
  }
7103
6958
  localLegacy = null;
7104
6959
  localStandard = null;
@@ -7106,20 +6961,27 @@ function useInterrupt(config) {
7106
6961
  onRunFailed: () => {
7107
6962
  localLegacy = null;
7108
6963
  localStandard = null;
7109
- interruptState.clear();
6964
+ interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
7110
6965
  setPending(null);
7111
6966
  }
7112
6967
  });
6968
+ interruptStateRef.current = agent.pendingInterrupts?.length ? (0, _copilotkit_core.ɵgetAgentInterruptState)(agent) : new _copilotkit_core.ɵInterruptState();
6969
+ setPending(interruptStateRef.current.pending);
7113
6970
  return () => {
7114
6971
  subscription.unsubscribe();
7115
- interruptState.clear();
6972
+ interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
7116
6973
  };
7117
6974
  }, [agent]);
6975
+ /** Record an explicit answer and resume once the complete batch is addressed. */
7118
6976
  const resolve = (0, react.useCallback)(async (payload, interruptId) => {
7119
6977
  const current = pendingRef.current;
7120
6978
  if (!current) return;
7121
6979
  if (current.kind === "standard" && current.interrupts.length > 1 && interruptId === void 0) console.warn(`[CopilotKit] useInterrupt: resolve()/cancel() called without an interruptId while ${current.interrupts.length} interrupts are open; defaulting to the first. Pass an interruptId to address a specific interrupt.`);
7122
- const decision = interruptStateRef.current.resolve(payload, interruptId);
6980
+ if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
6981
+ console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
6982
+ return;
6983
+ }
6984
+ const decision = interruptStateRef.current.resolve(payload, interruptId, agent.messages);
7123
6985
  if (decision.kind === "legacy-resume") try {
7124
6986
  return await copilotkit.runAgent({
7125
6987
  agent,
@@ -7135,7 +6997,7 @@ function useInterrupt(config) {
7135
6997
  }
7136
6998
  if (decision.kind === "expired") {
7137
6999
  console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
7138
- interruptStateRef.current.clear();
7000
+ interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
7139
7001
  setPending(null);
7140
7002
  return;
7141
7003
  }
@@ -7153,25 +7015,30 @@ function useInterrupt(config) {
7153
7015
  });
7154
7016
  } catch (err) {
7155
7017
  console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
7156
- interruptStateRef.current.clear();
7018
+ interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
7157
7019
  setPending(null);
7158
7020
  throw err;
7159
7021
  }
7160
7022
  }, [agent, copilotkit]);
7023
+ /** Cancel a standard interrupt or dismiss a legacy interrupt locally. */
7161
7024
  const cancel = (0, react.useCallback)(async (interruptId) => {
7162
7025
  const current = pendingRef.current;
7163
7026
  if (!current) return;
7164
7027
  if (current.kind === "standard" && current.interrupts.length > 1 && interruptId === void 0) console.warn(`[CopilotKit] useInterrupt: resolve()/cancel() called without an interruptId while ${current.interrupts.length} interrupts are open; defaulting to the first. Pass an interruptId to address a specific interrupt.`);
7165
- const decision = interruptStateRef.current.cancel(interruptId);
7028
+ if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
7029
+ console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
7030
+ return;
7031
+ }
7032
+ const decision = interruptStateRef.current.cancel(interruptId, agent.messages);
7166
7033
  if (decision.kind === "dismiss") {
7167
7034
  console.warn("[CopilotKit] useInterrupt: cancel() is not supported for legacy on_interrupt interrupts; dismissing.");
7168
- interruptStateRef.current.clear();
7035
+ interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
7169
7036
  setPending(null);
7170
7037
  return;
7171
7038
  }
7172
7039
  if (decision.kind === "expired") {
7173
7040
  console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
7174
- interruptStateRef.current.clear();
7041
+ interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
7175
7042
  setPending(null);
7176
7043
  return;
7177
7044
  }
@@ -7189,7 +7056,7 @@ function useInterrupt(config) {
7189
7056
  });
7190
7057
  } catch (err) {
7191
7058
  console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
7192
- interruptStateRef.current.clear();
7059
+ interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
7193
7060
  setPending(null);
7194
7061
  throw err;
7195
7062
  }
@@ -7204,6 +7071,7 @@ function useInterrupt(config) {
7204
7071
  resolveRef.current = resolve;
7205
7072
  const cancelRef = (0, react.useRef)(cancel);
7206
7073
  cancelRef.current = cancel;
7074
+ /** Evaluate the consumer filter, logging failures and disabling their UI. */
7207
7075
  const isEnabled = (event) => {
7208
7076
  const predicate = enabledRef.current;
7209
7077
  if (!predicate) return true;
@@ -10801,10 +10669,13 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10801
10669
  total: 0,
10802
10670
  sizes: /* @__PURE__ */ new Map()
10803
10671
  });
10672
+ const resizeAnchorRef = react.default.useRef(null);
10673
+ const restoringVisibilityRef = react.default.useRef(false);
10804
10674
  const firstMessageId = deduplicatedMessages[0]?.id;
10805
10675
  const measuredThreadRef = react.default.useRef(firstMessageId);
10806
10676
  if (measuredThreadRef.current !== firstMessageId) {
10807
10677
  measuredThreadRef.current = firstMessageId;
10678
+ resizeAnchorRef.current = null;
10808
10679
  measuredRef.current = {
10809
10680
  total: 0,
10810
10681
  sizes: /* @__PURE__ */ new Map()
@@ -10814,7 +10685,28 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10814
10685
  const { total, sizes } = measuredRef.current;
10815
10686
  return sizes.size > 0 ? Math.max(1, Math.round(total / sizes.size)) : 100;
10816
10687
  }, []);
10817
- const measureRowElement = react.default.useCallback((el) => {
10688
+ const isPinnedToBottomRef = react.default.useRef(isPinnedToBottom);
10689
+ const measuredWidthRef = react.default.useRef(null);
10690
+ const captureResizeAnchor = react.default.useCallback((instance) => {
10691
+ const width = instance.scrollElement?.clientWidth;
10692
+ if (!width || instance.scrollElement?.clientHeight === 0 || restoringVisibilityRef.current || isPinnedToBottomRef.current || instance.options.count === 0 || measuredWidthRef.current === null || width === measuredWidthRef.current) return;
10693
+ if (resizeAnchorRef.current) {
10694
+ if (resizeAnchorRef.current.ready) resizeAnchorRef.current = {
10695
+ ...resizeAnchorRef.current,
10696
+ ready: false
10697
+ };
10698
+ return;
10699
+ }
10700
+ const offset = instance.scrollElement?.scrollTop ?? 0;
10701
+ const anchor = instance.getVirtualItemForOffset(offset);
10702
+ if (anchor) resizeAnchorRef.current = {
10703
+ index: anchor.index,
10704
+ offset: offset - anchor.start,
10705
+ ready: false
10706
+ };
10707
+ }, []);
10708
+ const measureRowElement = react.default.useCallback((el, _entry, instance) => {
10709
+ captureResizeAnchor(instance);
10818
10710
  const height = el?.getBoundingClientRect().height ?? 0;
10819
10711
  const index = Number(el?.dataset?.index);
10820
10712
  if (height > 0 && Number.isInteger(index)) {
@@ -10823,16 +10715,70 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10823
10715
  sizes.set(index, height);
10824
10716
  }
10825
10717
  return height > 0 ? height : measuredRef.current.sizes.get(index) ?? 100;
10826
- }, []);
10827
- const isPinnedToBottomRef = react.default.useRef(isPinnedToBottom);
10718
+ }, [captureResizeAnchor]);
10828
10719
  const shouldAdjustScrollOnResize = react.default.useCallback((item, _delta, instance) => {
10829
- if (isPinnedToBottomRef.current) return false;
10720
+ if (isPinnedToBottomRef.current || resizeAnchorRef.current || restoringVisibilityRef.current) return false;
10830
10721
  const scrollAdjustments = instance.scrollAdjustments ?? 0;
10831
10722
  return item.start < (instance.scrollOffset ?? 0) + scrollAdjustments;
10832
10723
  }, []);
10724
+ const observeScrollRect = react.default.useCallback((instance, notify) => {
10725
+ let frame;
10726
+ let pendingRect;
10727
+ const disconnect = (0, _tanstack_react_virtual.observeElementRect)(instance, (rect) => {
10728
+ if (instance.scrollElement?.clientHeight === 0) {
10729
+ restoringVisibilityRef.current = true;
10730
+ resizeAnchorRef.current = null;
10731
+ if (frame !== void 0) cancelAnimationFrame(frame);
10732
+ frame = void 0;
10733
+ pendingRect = void 0;
10734
+ notify(rect);
10735
+ return;
10736
+ }
10737
+ const width = instance.scrollElement?.clientWidth ?? rect.width;
10738
+ const previousWidth = measuredWidthRef.current;
10739
+ if (width > 0 && width !== previousWidth) {
10740
+ captureResizeAnchor(instance);
10741
+ if (previousWidth !== null) {
10742
+ pendingRect = rect;
10743
+ if (frame === void 0) frame = requestAnimationFrame(() => {
10744
+ frame = void 0;
10745
+ const nextRect = pendingRect;
10746
+ pendingRect = void 0;
10747
+ if (!instance.scrollElement?.clientHeight) return;
10748
+ measuredWidthRef.current = instance.scrollElement?.clientWidth ?? nextRect.width;
10749
+ if (resizeAnchorRef.current) resizeAnchorRef.current.ready = true;
10750
+ instance.getTotalSize();
10751
+ measuredRef.current = {
10752
+ total: 0,
10753
+ sizes: /* @__PURE__ */ new Map()
10754
+ };
10755
+ instance.elementsCache.forEach((element) => {
10756
+ measureRowElement(element, void 0, instance);
10757
+ });
10758
+ instance.measure();
10759
+ instance.getTotalSize();
10760
+ instance.elementsCache.forEach((element) => {
10761
+ instance.measureElement(element);
10762
+ });
10763
+ notify(nextRect);
10764
+ });
10765
+ return;
10766
+ }
10767
+ measuredWidthRef.current = width;
10768
+ }
10769
+ if (pendingRect) pendingRect = rect;
10770
+ else notify(rect);
10771
+ });
10772
+ return () => {
10773
+ disconnect?.();
10774
+ if (frame !== void 0) cancelAnimationFrame(frame);
10775
+ resizeAnchorRef.current = null;
10776
+ };
10777
+ }, [captureResizeAnchor, measureRowElement]);
10833
10778
  const virtualizer = (0, _tanstack_react_virtual.useVirtualizer)({
10834
10779
  count: shouldVirtualize ? rows.length : 0,
10835
10780
  getScrollElement: () => shouldVirtualize ? scrollElement : null,
10781
+ observeElementRect: observeScrollRect,
10836
10782
  estimateSize: estimateRowSize,
10837
10783
  overscan: 5,
10838
10784
  measureElement: measureRowElement,
@@ -10843,6 +10789,19 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10843
10789
  });
10844
10790
  isPinnedToBottomRef.current = isPinnedToBottom;
10845
10791
  virtualizer.shouldAdjustScrollPositionOnItemSizeChange = shouldAdjustScrollOnResize;
10792
+ (0, react.useLayoutEffect)(() => {
10793
+ const anchor = resizeAnchorRef.current;
10794
+ if (!anchor?.ready || restoringVisibilityRef.current) return;
10795
+ const position = virtualizer.getOffsetForIndex(anchor.index, "start");
10796
+ if (position && !isPinnedToBottomRef.current) {
10797
+ const target = position[0] + anchor.offset;
10798
+ if (Math.abs((scrollElement?.scrollTop ?? 0) - target) > .5) virtualizer.scrollToOffset(target);
10799
+ }
10800
+ const frame = requestAnimationFrame(() => {
10801
+ if (resizeAnchorRef.current === anchor) resizeAnchorRef.current = null;
10802
+ });
10803
+ return () => cancelAnimationFrame(frame);
10804
+ });
10846
10805
  const lastEndAlignedFirstMessageRef = react.default.useRef(void 0);
10847
10806
  (0, react.useLayoutEffect)(() => {
10848
10807
  if (!shouldVirtualize || !rows.length) return;
@@ -10951,22 +10910,33 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10951
10910
  const observer = new ResizeObserver(() => {
10952
10911
  if (element.clientHeight === 0) {
10953
10912
  suspended = true;
10913
+ restoringVisibilityRef.current = true;
10914
+ resizeAnchorRef.current = null;
10954
10915
  cancelAnimationFrame(frame);
10955
10916
  return;
10956
10917
  }
10957
10918
  if (!suspended || !anchor) {
10958
10919
  suspended = false;
10920
+ restoringVisibilityRef.current = false;
10959
10921
  remember();
10960
10922
  return;
10961
10923
  }
10924
+ cancelAnimationFrame(frame);
10962
10925
  let attempts = 0;
10963
10926
  let stableFrames = 0;
10964
10927
  const restore = () => {
10965
10928
  if (!anchor || element.clientHeight === 0) return;
10929
+ if (isPinnedToBottomRef.current) {
10930
+ anchor = null;
10931
+ suspended = false;
10932
+ restoringVisibilityRef.current = false;
10933
+ return;
10934
+ }
10966
10935
  const index = rowKeysRef.current.indexOf(anchor.key);
10967
10936
  if (index < 0) {
10968
10937
  anchor = null;
10969
10938
  suspended = false;
10939
+ restoringVisibilityRef.current = false;
10970
10940
  return;
10971
10941
  }
10972
10942
  const row = visibleRows().find((row) => row.dataset.scrollAnchor === anchor.key);
@@ -10982,6 +10952,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10982
10952
  if (++attempts < 60 && stableFrames < 3) frame = requestAnimationFrame(restore);
10983
10953
  else {
10984
10954
  suspended = false;
10955
+ restoringVisibilityRef.current = false;
10985
10956
  remember();
10986
10957
  }
10987
10958
  };
@@ -10991,6 +10962,8 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10991
10962
  cancelAnimationFrame(frame);
10992
10963
  anchor = null;
10993
10964
  suspended = false;
10965
+ restoringVisibilityRef.current = false;
10966
+ resizeAnchorRef.current = null;
10994
10967
  };
10995
10968
  element.addEventListener("scroll", remember, { passive: true });
10996
10969
  element.addEventListener("wheel", interrupt, { passive: true });
@@ -11001,6 +10974,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
11001
10974
  return () => {
11002
10975
  cancelAnimationFrame(frame);
11003
10976
  observer.disconnect();
10977
+ restoringVisibilityRef.current = false;
11004
10978
  element.removeEventListener("scroll", remember);
11005
10979
  element.removeEventListener("wheel", interrupt);
11006
10980
  element.removeEventListener("touchstart", interrupt);
@@ -11044,7 +11018,8 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
11044
11018
  shouldVirtualize ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
11045
11019
  style: {
11046
11020
  height: virtualizer.getTotalSize(),
11047
- position: "relative"
11021
+ position: "relative",
11022
+ overflowAnchor: "none"
11048
11023
  },
11049
11024
  children: virtualizer.getVirtualItems().map((virtualItem) => {
11050
11025
  const row = rows[virtualItem.index];
@@ -11403,6 +11378,7 @@ function usePinToSend({ scrollRef, contentRef, spacerRef, topOffset = 16 }) {
11403
11378
  const lastNonceRef = (0, react.useRef)(-1);
11404
11379
  (0, react.useEffect)(() => {
11405
11380
  if (sendNonce === lastNonceRef.current) return;
11381
+ const previousNonce = lastNonceRef.current;
11406
11382
  lastNonceRef.current = sendNonce;
11407
11383
  if (!id) return;
11408
11384
  const scrollEl = scrollRef.current;
@@ -11418,7 +11394,9 @@ function usePinToSend({ scrollRef, contentRef, spacerRef, topOffset = 16 }) {
11418
11394
  const bubbleHeight = Math.max(0, userMessageHeight - paddingTop);
11419
11395
  const spacerHeight = Math.max(0, viewportHeight - bubbleHeight - topOffset);
11420
11396
  spacerEl.style.height = `${spacerHeight}px`;
11397
+ let pinned = false;
11421
11398
  const raf = requestAnimationFrame(() => {
11399
+ pinned = true;
11422
11400
  const targetTop = computeOffsetTop(targetEl, scrollEl) + paddingTop - topOffset;
11423
11401
  scrollEl.scrollTo({
11424
11402
  top: Math.max(0, targetTop),
@@ -11435,6 +11413,7 @@ function usePinToSend({ scrollRef, contentRef, spacerRef, topOffset = 16 }) {
11435
11413
  return () => {
11436
11414
  cancelAnimationFrame(raf);
11437
11415
  ro.disconnect();
11416
+ if (!pinned) lastNonceRef.current = previousNonce;
11438
11417
  };
11439
11418
  }, [
11440
11419
  id,
@@ -11466,7 +11445,7 @@ function DropOverlay() {
11466
11445
  })
11467
11446
  });
11468
11447
  }
11469
- 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, disclaimer, intelligenceIndicator, children, className, ...props }) {
11448
+ 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, disclaimer, intelligenceIndicator, children, className, ...props }) {
11470
11449
  const configuredThreadId = require_MarkdownSurfaces.useCopilotChatConfiguration()?.threadId;
11471
11450
  const [fallbackThreadId, setFallbackThreadId] = (0, react.useState)(messages[0]?.id);
11472
11451
  const previousMessageIds = (0, react.useRef)(/* @__PURE__ */ new Set());
@@ -11541,6 +11520,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11541
11520
  onSelectSuggestion,
11542
11521
  className: "cpk:mb-3 cpk:lg:ml-4 cpk:lg:mr-4 cpk:ml-0 cpk:mr-0"
11543
11522
  }) : null;
11523
+ const BoundConnectingIndicator = isConnecting && messages.length === 0 && connectingIndicator !== false ? renderSlot(connectingIndicator === true ? void 0 : connectingIndicator, CopilotChatView.ConnectingIndicator, {}) : null;
11544
11524
  const BoundScrollView = renderSlot(scrollView, CopilotChatView.ScrollView, {
11545
11525
  autoScroll,
11546
11526
  scrollThreadId,
@@ -11551,10 +11531,14 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11551
11531
  style: { paddingBottom: `${inputContainerHeight + (hasSuggestions ? 4 : 32)}px` },
11552
11532
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11553
11533
  className: "cpk:max-w-3xl cpk:mx-auto",
11554
- children: [BoundMessageView, hasSuggestions ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
11555
- className: "cpk:pl-0 cpk:pr-4 cpk:@3xl:px-0 cpk:mt-4",
11556
- children: BoundSuggestionView
11557
- }) : null]
11534
+ children: [
11535
+ BoundConnectingIndicator,
11536
+ BoundMessageView,
11537
+ hasSuggestions ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
11538
+ className: "cpk:pl-0 cpk:pr-4 cpk:@3xl:px-0 cpk:mt-4",
11539
+ children: BoundSuggestionView
11540
+ }) : null
11541
+ ]
11558
11542
  })
11559
11543
  })
11560
11544
  });
@@ -11592,6 +11576,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11592
11576
  "data-copilotkit": true,
11593
11577
  "data-testid": "copilot-chat",
11594
11578
  "data-copilot-running": isRunning ? "true" : "false",
11579
+ "data-copilot-connecting": isConnecting ? "true" : "false",
11595
11580
  onDragOver,
11596
11581
  onDragLeave,
11597
11582
  onDrop,
@@ -11602,6 +11587,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11602
11587
  }
11603
11588
  if (children) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
11604
11589
  "data-copilotkit": true,
11590
+ "data-copilot-connecting": isConnecting ? "true" : "false",
11605
11591
  style: { display: "contents" },
11606
11592
  children: children({
11607
11593
  messageView: BoundMessageView,
@@ -11614,6 +11600,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11614
11600
  "data-copilotkit": true,
11615
11601
  "data-testid": "copilot-chat",
11616
11602
  "data-copilot-running": isRunning ? "true" : "false",
11603
+ "data-copilot-connecting": isConnecting ? "true" : "false",
11617
11604
  onDragOver,
11618
11605
  onDragLeave,
11619
11606
  onDrop,
@@ -11829,13 +11816,15 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11829
11816
  if (mode === "pin-to-bottom") return;
11830
11817
  const scrollElement = nonAutoScrollEl;
11831
11818
  if (!scrollElement) return;
11819
+ const contentElement = contentRef.current;
11832
11820
  const checkScroll = () => {
11833
- setShowScrollButton(!(scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight < 10));
11821
+ setShowScrollButton((contentElement ? contentElement.getBoundingClientRect().bottom - scrollElement.getBoundingClientRect().bottom : scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight) >= 10);
11834
11822
  };
11835
11823
  checkScroll();
11836
11824
  scrollElement.addEventListener("scroll", checkScroll);
11837
11825
  const resizeObserver = new ResizeObserver(checkScroll);
11838
11826
  resizeObserver.observe(scrollElement);
11827
+ if (contentElement) resizeObserver.observe(contentElement);
11839
11828
  return () => {
11840
11829
  scrollElement.removeEventListener("scroll", checkScroll);
11841
11830
  resizeObserver.disconnect();
@@ -11918,6 +11907,22 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11918
11907
  className,
11919
11908
  ...props
11920
11909
  });
11910
+ _CopilotChatView.ConnectingIndicator = ({ className, ...props }) => {
11911
+ const labels = require_MarkdownSurfaces.useCopilotChatConfiguration()?.labels ?? require_MarkdownSurfaces.CopilotChatDefaultLabels;
11912
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11913
+ "data-testid": "copilot-connecting-indicator",
11914
+ role: "status",
11915
+ className: cn("cpk:flex cpk:justify-center cpk:py-8", className),
11916
+ ...props,
11917
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Loader2, {
11918
+ "aria-hidden": "true",
11919
+ className: "cpk:size-6 cpk:animate-spin cpk:text-muted-foreground"
11920
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
11921
+ className: "cpk:sr-only",
11922
+ children: labels.chatConnectingLabel
11923
+ })]
11924
+ });
11925
+ };
11921
11926
  _CopilotChatView.WelcomeMessage = ({ className, ...props }) => {
11922
11927
  const labels = require_MarkdownSurfaces.useCopilotChatConfiguration()?.labels ?? require_MarkdownSurfaces.CopilotChatDefaultLabels;
11923
11928
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h1", {
@@ -16528,4 +16533,4 @@ Object.defineProperty(exports, 'useToast', {
16528
16533
  return useToast;
16529
16534
  }
16530
16535
  });
16531
- //# sourceMappingURL=copilotkit-CVvbU9lV.cjs.map
16536
+ //# sourceMappingURL=copilotkit-BOTf5RHF.cjs.map