@galaxycore/ai-chat 0.11.0 → 0.12.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.0
4
+
5
+ - Upgrade Streamdown to 2.8 and make `MarkdownResponse` a complete assistant Markdown renderer: CJK-friendly emphasis (`@streamdown/cjk`), single-newline line breaks (`remark-breaks`), `<br>` tags outside code and tables treated as newlines (`normalizeBreakTags`), and code highlighting, KaTeX math and Mermaid diagrams loaded on demand only when a reply contains them. Code blocks show a copy button; line numbers are off so the block stays styled without Tailwind.
6
+ - Wrap tables in a labelled, keyboard-focusable scroll region (`tableLabel`). Add `className`, `renderLink`, `codeRenderers`, `remarkPlugins`, `components`, `translations`, `mode` and `tableLabel` to `MarkdownResponse` and export `MarkdownResponseProps` / `MarkdownLinkRenderer`. Remote images, non-HTTP(S) links and unsanitized HTML stay blocked by default.
7
+
8
+ ## 0.11.1
9
+
10
+ - Portal the `ChatContextUsage` breakdown popover into `document.body` with `position: fixed` anchored to the enclosing composer (`.gc-chat__composer` / `.ai-chat-composer`) and inheriting resolved theme variables, so scrollable or `overflow: hidden` composer containers never clip it.
11
+ - Add optional `hideWhenEmpty` prop to `ChatContextUsage` to hide the trigger cleanly when `usedTokens <= 0`.
12
+
3
13
  ## 0.11.0
4
14
 
5
15
  - Add Cursor-style context-window utilization UI and inline context-compaction divider (`ChatContextUsage`, `ChatCompactionNotice`, `CHAT_CONTEXT_USAGE_TONES`, `formatChatTokens`, `resolveChatContextUsage`), exported from both the root package and `/headless` (headless helpers).
package/README.md CHANGED
@@ -100,7 +100,7 @@ export function Conversation({ id, initialMessages = [] }: {
100
100
 
101
101
  `gateway.health()` 返回能力,宿主可据此显示功能。当前 pi 网关 `streaming/tools/cancel/sessionRestore=true`,`streamReplay/regenerate/attachments=false`;不要启用当前运行时不支持的重新生成或附件按钮。
102
102
 
103
- 助手回答默认渲染 Markdown,用户输入保留原文。Streamdown 随包自动安装;`renderText` 可覆盖默认渲染,`@galaxycore/ai-chat/markdown` 的 `MarkdownResponse` 入口保持兼容。包提供基础样式,无需 Tailwind;默认禁用远程图片加载,外链仅接受 HTTP(S)/站内绝对路径。数学公式、Mermaid 等插件由宿主按需接入。
103
+ 助手回答默认渲染 Markdown,用户输入保留原文。Streamdown 随包自动安装;`renderText` 可覆盖默认渲染,`@galaxycore/ai-chat/markdown` 的 `MarkdownResponse` 入口保持兼容。包提供基础样式,无需 Tailwind;默认禁用远程图片加载,外链仅接受 HTTP(S)/站内绝对路径。中日韩强调修复和单换行保留默认开启;代码高亮、数学公式和 Mermaid 按内容懒加载。宿主可通过 `renderLink`、`codeRenderers`、`remarkPlugins` 和 `components` 扩展。
104
104
 
105
105
  ## 三种使用层次
106
106
 
@@ -157,6 +157,8 @@ declare function resolveChatContextUsage(usage: ChatContextUsageData, options?:
157
157
  //#region src/context-usage-control.d.ts
158
158
  interface ChatContextUsageProps extends ChatContextUsageData {
159
159
  disabled?: boolean;
160
+ /** Hide the trigger completely when `usedTokens <= 0` (e.g. empty conversations). Defaults to false. */
161
+ hideWhenEmpty?: boolean;
160
162
  /** Percentage threshold for warning color. Defaults to 60. */
161
163
  warnThreshold?: number;
162
164
  /** Percentage threshold for high/danger color. Defaults to 85. */
@@ -182,9 +184,10 @@ interface ChatCompactionNoticeProps {
182
184
  }
183
185
  /**
184
186
  * Circular context-window utilization indicator for chat composers, opening a Cursor-style
185
- * segmented per-category token breakdown panel anchored above the composer.
187
+ * segmented per-category token breakdown panel portalled above the composer so overflow
188
+ * containers never clip it.
186
189
  */
187
- declare function ChatContextUsage({ usedTokens, contextWindowTokens, estimated, modelLabel, compacted, compactedSavedTokens, compactionCount, segments, disabled, warnThreshold, highThreshold, headerAction, open: controlledOpen, defaultOpen, onOpenChange, labels: overrides, className, popoverClassName }: ChatContextUsageProps): import("react").JSX.Element;
190
+ declare function ChatContextUsage({ usedTokens, contextWindowTokens, estimated, modelLabel, compacted, compactedSavedTokens, compactionCount, segments, disabled, hideWhenEmpty, warnThreshold, highThreshold, headerAction, open: controlledOpen, defaultOpen, onOpenChange, labels: overrides, className, popoverClassName }: ChatContextUsageProps): import("react").JSX.Element | null;
188
191
  /**
189
192
  * Calm inline horizontal divider rendered in the conversation stream when automatic
190
193
  * context compaction is running or completed on a turn.
@@ -575,4 +578,4 @@ declare function useChatBranches<T extends {
575
578
  }>(items: readonly T[], options?: Omit<ProjectChatBranchesOptions<T>, 'selections' | 'headId' | 'stopAtHead'>): ChatBranchesController<T>;
576
579
  //#endregion
577
580
  export { ResolvedChatContextUsageSegment as $, ToolPresentationResolver as A, resolveChatModelSelection as B, ChatScrollHandle as C, TextRenderer as D, PartRenderers as E, ChatModelOption as F, ChatContextUsageProps as G, ChatCompactionNotice as H, ChatModelSelection as I, ChatContextUsageLevel as J, CHAT_CONTEXT_USAGE_TONES as K, ChatReasoningEffort as L, ChatModelPicker as M, ChatModelPickerProps as N, ToolPart as O, CHAT_REASONING_EFFORTS as P, ResolvedChatContextUsage as Q, ResolvedChatModelSelection as R, ChatPanelProps as S, PartRendererProps as T, ChatCompactionNoticeProps as U, selectChatModel as V, ChatContextUsage as W, ChatContextUsageTone as X, ChatContextUsageSegment as Y, ResolveChatContextUsageOptions as Z, ChatBranchInfo as _, projectChatBranches as a, ComposerTriggerController as at, ChatMessageActionContext as b, zhCN as c, ParsedSkillMarkdown as ct, safeUrl as d, filterMentions as dt, formatChatTokens as et, useAiChat as f, filterSkills as ft, AttachmentOptions as g, useComposerTrigger as gt, AiChatProps as h, slugifySkillName as ht, ProjectChatBranchesOptions as i, ChatSkillItem as it, ToolRenderers as j, ToolPresentation as k, acceptsFile as l, UseComposerTriggerOptions as lt, AiChatOptions as m, replaceComposerTrigger as mt, ChatBranchesController as n, ChatComposerMenuAction as nt, useChatBranches as o, ComposerTriggerKind as ot, AiChatController as p, parseSkillMarkdown as pt, ChatContextUsageData as q, ChatBranchesState as r, ChatMentionItem as rt, enUS as s, ComposerTriggerMatch as st, ChatBranchProjection as t, resolveChatContextUsage as tt, getMessageText as u, detectComposerTrigger as ut, ChatComposerProps as v, ChatSuggestedAction as w, ChatMessagesProps as x, ChatLabels as y, isChatReasoningEffort as z };
578
- //# sourceMappingURL=branches-CZkkLIra.d.ts.map
581
+ //# sourceMappingURL=branches-BwA51zXG.d.ts.map
@@ -1,5 +1,5 @@
1
1
 
2
2
  import { ChatContextAdapter, ChatContextController, ChatContextItem, ChatContextOptions, ChatContextValue, ChatRequestContext, SelectedChatContextItem, TextSelectionAdapterOptions, createTextSelectionAdapter, useChatContext } from "./context.js";
3
3
  import { SpeechInputAdapter, SpeechInputController, SpeechInputError, SpeechInputOptions, SpeechInputResult, SpeechInputSession, SpeechInputStartOptions, createBrowserSpeechAdapter, defaultSpeechInputLabels, useSpeechInput } from "./voice.js";
4
- import { $ as ResolvedChatContextUsageSegment, A as ToolPresentationResolver, B as resolveChatModelSelection, C as ChatScrollHandle, D as TextRenderer, E as PartRenderers, F as ChatModelOption, I as ChatModelSelection, J as ChatContextUsageLevel, K as CHAT_CONTEXT_USAGE_TONES, L as ChatReasoningEffort, O as ToolPart, P as CHAT_REASONING_EFFORTS, Q as ResolvedChatContextUsage, R as ResolvedChatModelSelection, S as ChatPanelProps, T as PartRendererProps, V as selectChatModel, X as ChatContextUsageTone, Y as ChatContextUsageSegment, Z as ResolveChatContextUsageOptions, _ as ChatBranchInfo, a as projectChatBranches, at as ComposerTriggerController, b as ChatMessageActionContext, c as zhCN, ct as ParsedSkillMarkdown, d as safeUrl, dt as filterMentions, et as formatChatTokens, f as useAiChat, ft as filterSkills, g as AttachmentOptions, gt as useComposerTrigger, h as AiChatProps, ht as slugifySkillName, i as ProjectChatBranchesOptions, it as ChatSkillItem, j as ToolRenderers, k as ToolPresentation, l as acceptsFile, lt as UseComposerTriggerOptions, m as AiChatOptions, mt as replaceComposerTrigger, n as ChatBranchesController, nt as ChatComposerMenuAction, o as useChatBranches, ot as ComposerTriggerKind, p as AiChatController, pt as parseSkillMarkdown, q as ChatContextUsageData, r as ChatBranchesState, rt as ChatMentionItem, s as enUS, st as ComposerTriggerMatch, t as ChatBranchProjection, tt as resolveChatContextUsage, u as getMessageText, ut as detectComposerTrigger, v as ChatComposerProps, w as ChatSuggestedAction, x as ChatMessagesProps, y as ChatLabels, z as isChatReasoningEffort } from "./branches-CZkkLIra.js";
4
+ import { $ as ResolvedChatContextUsageSegment, A as ToolPresentationResolver, B as resolveChatModelSelection, C as ChatScrollHandle, D as TextRenderer, E as PartRenderers, F as ChatModelOption, I as ChatModelSelection, J as ChatContextUsageLevel, K as CHAT_CONTEXT_USAGE_TONES, L as ChatReasoningEffort, O as ToolPart, P as CHAT_REASONING_EFFORTS, Q as ResolvedChatContextUsage, R as ResolvedChatModelSelection, S as ChatPanelProps, T as PartRendererProps, V as selectChatModel, X as ChatContextUsageTone, Y as ChatContextUsageSegment, Z as ResolveChatContextUsageOptions, _ as ChatBranchInfo, a as projectChatBranches, at as ComposerTriggerController, b as ChatMessageActionContext, c as zhCN, ct as ParsedSkillMarkdown, d as safeUrl, dt as filterMentions, et as formatChatTokens, f as useAiChat, ft as filterSkills, g as AttachmentOptions, gt as useComposerTrigger, h as AiChatProps, ht as slugifySkillName, i as ProjectChatBranchesOptions, it as ChatSkillItem, j as ToolRenderers, k as ToolPresentation, l as acceptsFile, lt as UseComposerTriggerOptions, m as AiChatOptions, mt as replaceComposerTrigger, n as ChatBranchesController, nt as ChatComposerMenuAction, o as useChatBranches, ot as ComposerTriggerKind, p as AiChatController, pt as parseSkillMarkdown, q as ChatContextUsageData, r as ChatBranchesState, rt as ChatMentionItem, s as enUS, st as ComposerTriggerMatch, t as ChatBranchProjection, tt as resolveChatContextUsage, u as getMessageText, ut as detectComposerTrigger, v as ChatComposerProps, w as ChatSuggestedAction, x as ChatMessagesProps, y as ChatLabels, z as isChatReasoningEffort } from "./branches-BwA51zXG.js";
5
5
  export { type AiChatController, type AiChatOptions, type AiChatProps, type AttachmentOptions, CHAT_CONTEXT_USAGE_TONES, CHAT_REASONING_EFFORTS, type ChatBranchInfo, type ChatBranchProjection, type ChatBranchesController, type ChatBranchesState, type ChatComposerMenuAction, type ChatComposerProps, type ChatContextAdapter, type ChatContextController, type ChatContextItem, type ChatContextOptions, type ChatContextUsageData, type ChatContextUsageLevel, type ChatContextUsageSegment, type ChatContextUsageTone, type ChatContextValue, type ChatLabels, type ChatMentionItem, type ChatMessageActionContext, type ChatMessagesProps, type ChatModelOption, type ChatModelSelection, type ChatPanelProps, type ChatReasoningEffort, type ChatRequestContext, type ChatScrollHandle, type ChatSkillItem, type ChatSuggestedAction, type ComposerTriggerController, type ComposerTriggerKind, type ComposerTriggerMatch, type ParsedSkillMarkdown, type PartRendererProps, type PartRenderers, type ProjectChatBranchesOptions, type ResolveChatContextUsageOptions, type ResolvedChatContextUsage, type ResolvedChatContextUsageSegment, type ResolvedChatModelSelection, type SelectedChatContextItem, type SpeechInputAdapter, type SpeechInputController, SpeechInputError, type SpeechInputOptions, type SpeechInputResult, type SpeechInputSession, type SpeechInputStartOptions, type TextRenderer, type TextSelectionAdapterOptions, type ToolPart, type ToolPresentation, type ToolPresentationResolver, type ToolRenderers, type UseComposerTriggerOptions, acceptsFile, createBrowserSpeechAdapter, createTextSelectionAdapter, defaultSpeechInputLabels, detectComposerTrigger, enUS, filterMentions, filterSkills, formatChatTokens, getMessageText, isChatReasoningEffort, parseSkillMarkdown, projectChatBranches, replaceComposerTrigger, resolveChatContextUsage, resolveChatModelSelection, safeUrl, selectChatModel, slugifySkillName, useAiChat, useChatBranches, useChatContext, useComposerTrigger, useSpeechInput, zhCN };
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { a as ChatIconProps, i as ChatIconOverrides, n as ChatAppearanceProvider
3
3
  import { n as ChatIconButtonProps, t as ChatIconButton } from "./appearance-CdnhPTwk.js";
4
4
  import { ChatContextAdapter, ChatContextController, ChatContextItem, ChatContextOptions, ChatContextValue, ChatRequestContext, ContextTray, ContextTrayLabels, ContextTrayProps, SelectedChatContextItem, TextSelectionAdapterOptions, createTextSelectionAdapter, useChatContext } from "./context.js";
5
5
  import { SpeechInputAdapter, SpeechInputController, SpeechInputError, SpeechInputErrorCode, SpeechInputLabels, SpeechInputOptions, SpeechInputResult, SpeechInputSession, SpeechInputStartOptions, SpeechInputState, SpeechInputSupport, UseSpeechInputOptions, createBrowserSpeechAdapter, defaultSpeechInputLabels, useSpeechInput } from "./voice.js";
6
- import { $ as ResolvedChatContextUsageSegment, A as ToolPresentationResolver, B as resolveChatModelSelection, C as ChatScrollHandle, D as TextRenderer, E as PartRenderers, F as ChatModelOption, G as ChatContextUsageProps, H as ChatCompactionNotice, I as ChatModelSelection, J as ChatContextUsageLevel, K as CHAT_CONTEXT_USAGE_TONES, L as ChatReasoningEffort, M as ChatModelPicker, N as ChatModelPickerProps, O as ToolPart, P as CHAT_REASONING_EFFORTS, Q as ResolvedChatContextUsage, R as ResolvedChatModelSelection, S as ChatPanelProps, T as PartRendererProps, U as ChatCompactionNoticeProps, V as selectChatModel, W as ChatContextUsage, X as ChatContextUsageTone, Y as ChatContextUsageSegment, Z as ResolveChatContextUsageOptions, _ as ChatBranchInfo, a as projectChatBranches, at as ComposerTriggerController, b as ChatMessageActionContext, c as zhCN, ct as ParsedSkillMarkdown, dt as filterMentions, et as formatChatTokens, f as useAiChat, ft as filterSkills, g as AttachmentOptions, gt as useComposerTrigger, h as AiChatProps, ht as slugifySkillName, i as ProjectChatBranchesOptions, it as ChatSkillItem, j as ToolRenderers, k as ToolPresentation, lt as UseComposerTriggerOptions, m as AiChatOptions, mt as replaceComposerTrigger, n as ChatBranchesController, nt as ChatComposerMenuAction, o as useChatBranches, ot as ComposerTriggerKind, p as AiChatController, pt as parseSkillMarkdown, q as ChatContextUsageData, r as ChatBranchesState, rt as ChatMentionItem, s as enUS, st as ComposerTriggerMatch, t as ChatBranchProjection, tt as resolveChatContextUsage, u as getMessageText, ut as detectComposerTrigger, v as ChatComposerProps, w as ChatSuggestedAction, x as ChatMessagesProps, y as ChatLabels, z as isChatReasoningEffort } from "./branches-CZkkLIra.js";
6
+ import { $ as ResolvedChatContextUsageSegment, A as ToolPresentationResolver, B as resolveChatModelSelection, C as ChatScrollHandle, D as TextRenderer, E as PartRenderers, F as ChatModelOption, G as ChatContextUsageProps, H as ChatCompactionNotice, I as ChatModelSelection, J as ChatContextUsageLevel, K as CHAT_CONTEXT_USAGE_TONES, L as ChatReasoningEffort, M as ChatModelPicker, N as ChatModelPickerProps, O as ToolPart, P as CHAT_REASONING_EFFORTS, Q as ResolvedChatContextUsage, R as ResolvedChatModelSelection, S as ChatPanelProps, T as PartRendererProps, U as ChatCompactionNoticeProps, V as selectChatModel, W as ChatContextUsage, X as ChatContextUsageTone, Y as ChatContextUsageSegment, Z as ResolveChatContextUsageOptions, _ as ChatBranchInfo, a as projectChatBranches, at as ComposerTriggerController, b as ChatMessageActionContext, c as zhCN, ct as ParsedSkillMarkdown, dt as filterMentions, et as formatChatTokens, f as useAiChat, ft as filterSkills, g as AttachmentOptions, gt as useComposerTrigger, h as AiChatProps, ht as slugifySkillName, i as ProjectChatBranchesOptions, it as ChatSkillItem, j as ToolRenderers, k as ToolPresentation, lt as UseComposerTriggerOptions, m as AiChatOptions, mt as replaceComposerTrigger, n as ChatBranchesController, nt as ChatComposerMenuAction, o as useChatBranches, ot as ComposerTriggerKind, p as AiChatController, pt as parseSkillMarkdown, q as ChatContextUsageData, r as ChatBranchesState, rt as ChatMentionItem, s as enUS, st as ComposerTriggerMatch, t as ChatBranchProjection, tt as resolveChatContextUsage, u as getMessageText, ut as detectComposerTrigger, v as ChatComposerProps, w as ChatSuggestedAction, x as ChatMessagesProps, y as ChatLabels, z as isChatReasoningEffort } from "./branches-BwA51zXG.js";
7
7
  import { ActiveMarquee, ChatTargetHit, ChatTargetKind, ChatTargetRect, ChatTargetingController, ChatTargetingLabels, ChatTargetingOverlay, ChatTargetingOverlayProps, PendingChatTarget, UseChatTargetingOptions, enUSTargetingLabels, toChatContextItem, useChatTargeting, zhCNTargetingLabels } from "./targeting.js";
8
8
  import { HTMLAttributes, ReactNode } from "react";
9
9
  import { UIMessage } from "ai";
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import "./appearance.js";
10
10
  import { ChatTargetingOverlay, enUSTargetingLabels, toChatContextItem, useChatTargeting, zhCNTargetingLabels } from "./targeting.js";
11
11
  import { useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
12
12
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
13
+ import { createPortal } from "react-dom";
13
14
  import { isToolUIPart } from "ai";
14
15
  //#region src/composer-popovers.tsx
15
16
  function ChatSlashMenu({ skills, activeIndex, onHighlight, onSelect, onAddSkill, onBrowseSkills, labels: overrides, className = "" }) {
@@ -335,38 +336,146 @@ function interpolate(template, values) {
335
336
  }
336
337
  const RING_RADIUS = 7;
337
338
  const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS;
339
+ const COMPOSER_SELECTOR = ".gc-chat__composer, .ai-chat-composer";
340
+ const PORTAL_TOKEN_NAMES = [
341
+ "--gc-chat-bg",
342
+ "--gc-chat-popover-bg",
343
+ "--gc-chat-popover-shadow",
344
+ "--gc-chat-surface",
345
+ "--gc-chat-surface-hover",
346
+ "--gc-chat-text",
347
+ "--gc-chat-muted",
348
+ "--gc-chat-border",
349
+ "--gc-chat-border-strong",
350
+ "--gc-chat-focus",
351
+ "--gc-chat-warning",
352
+ "--gc-chat-danger",
353
+ "--gc-chat-ctx-slate",
354
+ "--gc-chat-ctx-violet",
355
+ "--gc-chat-ctx-green",
356
+ "--gc-chat-ctx-amber",
357
+ "--gc-chat-ctx-magenta",
358
+ "--gc-chat-ctx-blue",
359
+ "--gc-chat-ctx-orange",
360
+ "--gc-chat-ctx-teal"
361
+ ];
362
+ function computePopoverMetrics(root, trigger) {
363
+ const composer = trigger.closest(COMPOSER_SELECTOR);
364
+ const rect = (composer ?? trigger).getBoundingClientRect();
365
+ const computed = window.getComputedStyle(root);
366
+ const theme = root.closest("[data-theme]")?.getAttribute("data-theme") ?? root.ownerDocument.documentElement.getAttribute("data-theme") ?? void 0;
367
+ const vars = {};
368
+ for (const name of PORTAL_TOKEN_NAMES) {
369
+ const value = computed.getPropertyValue(name).trim();
370
+ if (value) vars[name] = value;
371
+ }
372
+ const viewportWidth = window.innerWidth || 1024;
373
+ const viewportHeight = window.innerHeight || 768;
374
+ const margin = 12;
375
+ const gap = 8;
376
+ const style = {
377
+ ...vars,
378
+ fontFamily: computed.fontFamily || void 0
379
+ };
380
+ if (rect.width > 0 || rect.height > 0) {
381
+ const targetWidth = composer ? Math.min(rect.width, Math.max(240, viewportWidth - 24)) : Math.min(360, Math.max(240, viewportWidth - 24));
382
+ const rawLeft = composer ? rect.left : rect.right - targetWidth;
383
+ style.left = Math.max(margin, Math.min(viewportWidth - targetWidth - margin, rawLeft));
384
+ style.width = targetWidth;
385
+ const spaceAbove = rect.top - gap - margin;
386
+ const spaceBelow = viewportHeight - rect.bottom - gap - margin;
387
+ if (spaceAbove >= 180 || spaceAbove >= spaceBelow) {
388
+ style.bottom = Math.max(margin, viewportHeight - rect.top + gap);
389
+ style.top = "auto";
390
+ style.maxHeight = Math.max(160, spaceAbove);
391
+ } else {
392
+ style.top = Math.max(margin, rect.bottom + gap);
393
+ style.bottom = "auto";
394
+ style.maxHeight = Math.max(160, spaceBelow);
395
+ }
396
+ }
397
+ return {
398
+ style,
399
+ theme
400
+ };
401
+ }
338
402
  /**
339
403
  * Circular context-window utilization indicator for chat composers, opening a Cursor-style
340
- * segmented per-category token breakdown panel anchored above the composer.
404
+ * segmented per-category token breakdown panel portalled above the composer so overflow
405
+ * containers never clip it.
341
406
  */
342
- function ChatContextUsage({ usedTokens, contextWindowTokens, estimated = true, modelLabel, compacted = false, compactedSavedTokens = 0, compactionCount = 0, segments, disabled = false, warnThreshold, highThreshold, headerAction, open: controlledOpen, defaultOpen = false, onOpenChange, labels: overrides, className = "", popoverClassName = "" }) {
407
+ function ChatContextUsage({ usedTokens, contextWindowTokens, estimated = true, modelLabel, compacted = false, compactedSavedTokens = 0, compactionCount = 0, segments, disabled = false, hideWhenEmpty = false, warnThreshold, highThreshold, headerAction, open: controlledOpen, defaultOpen = false, onOpenChange, labels: overrides, className = "", popoverClassName = "" }) {
343
408
  const labels = resolveLabels(overrides);
344
409
  const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
345
410
  const isControlled = controlledOpen !== void 0;
346
- const open = !disabled && (isControlled ? controlledOpen : uncontrolledOpen);
347
411
  const rootRef = useRef(null);
348
412
  const triggerRef = useRef(null);
413
+ const popoverRef = useRef(null);
349
414
  const onOpenChangeRef = useRef(onOpenChange);
350
415
  onOpenChangeRef.current = onOpenChange;
351
416
  const dialogId = useId();
417
+ const [metrics, setMetrics] = useState();
418
+ const resolved = resolveChatContextUsage({
419
+ usedTokens,
420
+ contextWindowTokens,
421
+ estimated,
422
+ modelLabel,
423
+ compacted,
424
+ compactedSavedTokens,
425
+ compactionCount,
426
+ segments
427
+ }, {
428
+ warnThreshold,
429
+ highThreshold
430
+ });
431
+ const hidden = hideWhenEmpty && resolved.usedTokens <= 0;
432
+ const open = !disabled && !hidden && (isControlled ? controlledOpen : uncontrolledOpen);
352
433
  function setOpen(next) {
353
434
  if (!isControlled) setUncontrolledOpen(next);
354
435
  onOpenChangeRef.current?.(next);
355
436
  }
356
437
  useEffect(() => {
357
- if (disabled && !isControlled && uncontrolledOpen) setUncontrolledOpen(false);
438
+ if ((disabled || hidden) && !isControlled && uncontrolledOpen) setUncontrolledOpen(false);
358
439
  }, [
359
440
  disabled,
441
+ hidden,
360
442
  isControlled,
361
443
  uncontrolledOpen
362
444
  ]);
445
+ useLayoutEffect(() => {
446
+ if (!open) return;
447
+ const root = rootRef.current;
448
+ const trigger = triggerRef.current;
449
+ if (!root || !trigger) return;
450
+ const update = () => {
451
+ if (!root.isConnected || !trigger.isConnected) return;
452
+ setMetrics(computePopoverMetrics(root, trigger));
453
+ };
454
+ update();
455
+ const composer = trigger.closest(COMPOSER_SELECTOR);
456
+ const resizeObserver = typeof ResizeObserver !== "undefined" && composer ? new ResizeObserver(update) : null;
457
+ if (resizeObserver && composer) resizeObserver.observe(composer);
458
+ window.addEventListener("resize", update);
459
+ window.addEventListener("scroll", update, true);
460
+ return () => {
461
+ resizeObserver?.disconnect();
462
+ window.removeEventListener("resize", update);
463
+ window.removeEventListener("scroll", update, true);
464
+ };
465
+ }, [
466
+ open,
467
+ usedTokens,
468
+ contextWindowTokens,
469
+ resolved.visibleSegments.length
470
+ ]);
363
471
  useEffect(() => {
364
472
  if (!open) return;
365
473
  function onPointerDown(event) {
366
- if (rootRef.current && !rootRef.current.contains(event.target)) {
367
- if (!isControlled) setUncontrolledOpen(false);
368
- onOpenChangeRef.current?.(false);
369
- }
474
+ const target = event.target;
475
+ if (!target) return;
476
+ if (rootRef.current?.contains(target) || popoverRef.current?.contains(target)) return;
477
+ if (!isControlled) setUncontrolledOpen(false);
478
+ onOpenChangeRef.current?.(false);
370
479
  }
371
480
  function onKeyDown(event) {
372
481
  if (event.key === "Escape") {
@@ -383,19 +492,7 @@ function ChatContextUsage({ usedTokens, contextWindowTokens, estimated = true, m
383
492
  document.removeEventListener("keydown", onKeyDown);
384
493
  };
385
494
  }, [open, isControlled]);
386
- const resolved = resolveChatContextUsage({
387
- usedTokens,
388
- contextWindowTokens,
389
- estimated,
390
- modelLabel,
391
- compacted,
392
- compactedSavedTokens,
393
- compactionCount,
394
- segments
395
- }, {
396
- warnThreshold,
397
- highThreshold
398
- });
495
+ if (hidden) return null;
399
496
  const dashOffset = RING_CIRCUMFERENCE * (1 - resolved.ratio);
400
497
  const triggerLabel = interpolate(labels.contextUsageTrigger, {
401
498
  percent: resolved.percent,
@@ -407,6 +504,115 @@ function ChatContextUsage({ usedTokens, contextWindowTokens, estimated = true, m
407
504
  used: resolved.usedDisplay,
408
505
  window: resolved.windowFormatted
409
506
  });
507
+ const popoverNode = open ? /* @__PURE__ */ jsx("div", {
508
+ ref: popoverRef,
509
+ id: dialogId,
510
+ role: "dialog",
511
+ "aria-label": labels.contextUsage,
512
+ "data-theme": metrics?.theme,
513
+ style: metrics?.style,
514
+ className: `gc-chat__popover gc-chat__context-usage-popover ${popoverClassName}`.trim(),
515
+ children: /* @__PURE__ */ jsxs("div", {
516
+ className: "gc-chat__context-usage-panel",
517
+ children: [
518
+ /* @__PURE__ */ jsxs("div", {
519
+ className: "gc-chat__context-usage-header",
520
+ children: [/* @__PURE__ */ jsxs("div", {
521
+ className: "gc-chat__context-usage-heading",
522
+ children: [
523
+ /* @__PURE__ */ jsx("span", {
524
+ className: "gc-chat__context-usage-title",
525
+ children: labels.contextUsage
526
+ }),
527
+ resolved.modelLabel ? /* @__PURE__ */ jsx("span", {
528
+ className: "gc-chat__context-usage-model",
529
+ title: resolved.modelLabel,
530
+ children: resolved.modelLabel
531
+ }) : null,
532
+ headerAction
533
+ ]
534
+ }), /* @__PURE__ */ jsx("button", {
535
+ type: "button",
536
+ className: "gc-chat__context-usage-close",
537
+ "aria-label": labels.contextUsageClose,
538
+ onClick: () => {
539
+ setOpen(false);
540
+ triggerRef.current?.focus();
541
+ },
542
+ children: /* @__PURE__ */ jsx(Icon, {
543
+ name: "minus",
544
+ width: 15,
545
+ height: 15
546
+ })
547
+ })]
548
+ }),
549
+ /* @__PURE__ */ jsxs("div", {
550
+ className: "gc-chat__context-usage-meter",
551
+ children: [/* @__PURE__ */ jsxs("div", {
552
+ className: "gc-chat__context-usage-summary",
553
+ children: [/* @__PURE__ */ jsx("span", {
554
+ className: "gc-chat__context-usage-percent",
555
+ "data-level": resolved.level,
556
+ children: percentLabel
557
+ }), /* @__PURE__ */ jsx("span", {
558
+ className: "gc-chat__context-usage-tokens",
559
+ children: tokensRatioLabel
560
+ })]
561
+ }), /* @__PURE__ */ jsx("div", {
562
+ className: "gc-chat__context-usage-bar",
563
+ role: "meter",
564
+ "aria-label": labels.contextUsage,
565
+ "aria-valuemin": 0,
566
+ "aria-valuemax": resolved.contextWindowTokens,
567
+ "aria-valuenow": resolved.usedTokens,
568
+ children: resolved.visibleSegments.length > 0 && resolved.usedTokens > 0 ? /* @__PURE__ */ jsx("div", {
569
+ className: "gc-chat__context-usage-bar-fill",
570
+ style: { width: `${resolved.fillPercent}%` },
571
+ children: resolved.visibleSegments.map((segment) => /* @__PURE__ */ jsx("span", {
572
+ className: "gc-chat__context-usage-bar-segment",
573
+ "data-tone": segment.tone,
574
+ style: { flexGrow: segment.tokens },
575
+ title: interpolate(labels.contextUsageSegment, {
576
+ label: segment.label,
577
+ tokens: formatChatTokens(segment.tokens)
578
+ })
579
+ }, segment.id))
580
+ }) : null
581
+ })]
582
+ }),
583
+ resolved.visibleSegments.length > 0 ? /* @__PURE__ */ jsx("ul", {
584
+ className: "gc-chat__context-usage-legend",
585
+ children: resolved.visibleSegments.map((segment) => /* @__PURE__ */ jsxs("li", {
586
+ className: "gc-chat__context-usage-legend-row",
587
+ children: [/* @__PURE__ */ jsxs("span", {
588
+ className: "gc-chat__context-usage-legend-label",
589
+ children: [/* @__PURE__ */ jsx("span", {
590
+ className: "gc-chat__context-usage-swatch",
591
+ "data-tone": segment.tone,
592
+ "aria-hidden": "true"
593
+ }), /* @__PURE__ */ jsx("span", { children: segment.label })]
594
+ }), /* @__PURE__ */ jsx("span", {
595
+ className: "gc-chat__context-usage-legend-value",
596
+ children: formatChatTokens(segment.tokens)
597
+ })]
598
+ }, segment.id))
599
+ }) : /* @__PURE__ */ jsx("p", {
600
+ className: "gc-chat__context-usage-empty",
601
+ children: labels.contextUsageEmpty
602
+ }),
603
+ resolved.compacted ? /* @__PURE__ */ jsxs("div", {
604
+ className: "gc-chat__context-usage-compacted",
605
+ role: "status",
606
+ children: [/* @__PURE__ */ jsx(Icon, {
607
+ name: "minimize",
608
+ width: 13,
609
+ height: 13
610
+ }), /* @__PURE__ */ jsx("span", { children: resolved.compactedSavedTokens > 0 ? interpolate(labels.contextCompactedSaved, { saved: formatChatTokens(resolved.compactedSavedTokens) }) : labels.contextCompacted })]
611
+ }) : null
612
+ ]
613
+ })
614
+ }) : null;
615
+ const portalTarget = rootRef.current?.ownerDocument.body ?? (typeof document !== "undefined" ? document.body : null);
410
616
  return /* @__PURE__ */ jsxs("div", {
411
617
  ref: rootRef,
412
618
  className: `gc-chat__context-usage ${className}`.trim(),
@@ -442,111 +648,7 @@ function ChatContextUsage({ usedTokens, contextWindowTokens, estimated = true, m
442
648
  strokeDashoffset: dashOffset
443
649
  }) : null]
444
650
  })
445
- }), open ? /* @__PURE__ */ jsx("div", {
446
- id: dialogId,
447
- role: "dialog",
448
- "aria-label": labels.contextUsage,
449
- className: `gc-chat__popover gc-chat__context-usage-popover ${popoverClassName}`.trim(),
450
- children: /* @__PURE__ */ jsxs("div", {
451
- className: "gc-chat__context-usage-panel",
452
- children: [
453
- /* @__PURE__ */ jsxs("div", {
454
- className: "gc-chat__context-usage-header",
455
- children: [/* @__PURE__ */ jsxs("div", {
456
- className: "gc-chat__context-usage-heading",
457
- children: [
458
- /* @__PURE__ */ jsx("span", {
459
- className: "gc-chat__context-usage-title",
460
- children: labels.contextUsage
461
- }),
462
- resolved.modelLabel ? /* @__PURE__ */ jsx("span", {
463
- className: "gc-chat__context-usage-model",
464
- title: resolved.modelLabel,
465
- children: resolved.modelLabel
466
- }) : null,
467
- headerAction
468
- ]
469
- }), /* @__PURE__ */ jsx("button", {
470
- type: "button",
471
- className: "gc-chat__context-usage-close",
472
- "aria-label": labels.contextUsageClose,
473
- onClick: () => {
474
- setOpen(false);
475
- triggerRef.current?.focus();
476
- },
477
- children: /* @__PURE__ */ jsx(Icon, {
478
- name: "minus",
479
- width: 15,
480
- height: 15
481
- })
482
- })]
483
- }),
484
- /* @__PURE__ */ jsxs("div", {
485
- className: "gc-chat__context-usage-meter",
486
- children: [/* @__PURE__ */ jsxs("div", {
487
- className: "gc-chat__context-usage-summary",
488
- children: [/* @__PURE__ */ jsx("span", {
489
- className: "gc-chat__context-usage-percent",
490
- "data-level": resolved.level,
491
- children: percentLabel
492
- }), /* @__PURE__ */ jsx("span", {
493
- className: "gc-chat__context-usage-tokens",
494
- children: tokensRatioLabel
495
- })]
496
- }), /* @__PURE__ */ jsx("div", {
497
- className: "gc-chat__context-usage-bar",
498
- role: "meter",
499
- "aria-label": labels.contextUsage,
500
- "aria-valuemin": 0,
501
- "aria-valuemax": resolved.contextWindowTokens,
502
- "aria-valuenow": resolved.usedTokens,
503
- children: resolved.visibleSegments.length > 0 && resolved.usedTokens > 0 ? /* @__PURE__ */ jsx("div", {
504
- className: "gc-chat__context-usage-bar-fill",
505
- style: { width: `${resolved.fillPercent}%` },
506
- children: resolved.visibleSegments.map((segment) => /* @__PURE__ */ jsx("span", {
507
- className: "gc-chat__context-usage-bar-segment",
508
- "data-tone": segment.tone,
509
- style: { flexGrow: segment.tokens },
510
- title: interpolate(labels.contextUsageSegment, {
511
- label: segment.label,
512
- tokens: formatChatTokens(segment.tokens)
513
- })
514
- }, segment.id))
515
- }) : null
516
- })]
517
- }),
518
- resolved.visibleSegments.length > 0 ? /* @__PURE__ */ jsx("ul", {
519
- className: "gc-chat__context-usage-legend",
520
- children: resolved.visibleSegments.map((segment) => /* @__PURE__ */ jsxs("li", {
521
- className: "gc-chat__context-usage-legend-row",
522
- children: [/* @__PURE__ */ jsxs("span", {
523
- className: "gc-chat__context-usage-legend-label",
524
- children: [/* @__PURE__ */ jsx("span", {
525
- className: "gc-chat__context-usage-swatch",
526
- "data-tone": segment.tone,
527
- "aria-hidden": "true"
528
- }), /* @__PURE__ */ jsx("span", { children: segment.label })]
529
- }), /* @__PURE__ */ jsx("span", {
530
- className: "gc-chat__context-usage-legend-value",
531
- children: formatChatTokens(segment.tokens)
532
- })]
533
- }, segment.id))
534
- }) : /* @__PURE__ */ jsx("p", {
535
- className: "gc-chat__context-usage-empty",
536
- children: labels.contextUsageEmpty
537
- }),
538
- resolved.compacted ? /* @__PURE__ */ jsxs("div", {
539
- className: "gc-chat__context-usage-compacted",
540
- role: "status",
541
- children: [/* @__PURE__ */ jsx(Icon, {
542
- name: "minimize",
543
- width: 13,
544
- height: 13
545
- }), /* @__PURE__ */ jsx("span", { children: resolved.compactedSavedTokens > 0 ? interpolate(labels.contextCompactedSaved, { saved: formatChatTokens(resolved.compactedSavedTokens) }) : labels.contextCompacted })]
546
- }) : null
547
- ]
548
- })
549
- }) : null]
651
+ }), popoverNode ? portalTarget ? createPortal(popoverNode, portalTarget) : popoverNode : null]
550
652
  });
551
653
  }
552
654
  /**