Skip to content

feat(ui): add @mention and /command suggestions to ChatComposer - #6225

Merged
saddlepaddle merged 49 commits into
mainfrom
chat-composer-suggestions
Aug 12, 2026
Merged

saddlepaddle merged 49 commits into
mainfrom
chat-composer-suggestions

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

What

Two commits:

  1. ChatComposer base component (cherry-picked — it was pushed to the feat(ui): add ChatHistorySidebar message rail with Storybook setup #6163 branch a few hours after that PR merged, so it never landed on main): Codex-style chat input with auto-growing textarea (IME-safe Enter-to-send via isEnterSubmit), platform-aware ⌘L/Ctrl L focus hint chip backed by a real global shortcut listener, a toolbar slot for app-owned controls, optional attach button, and a status-aware send button (disabled → primary arrow → stop square while status="streaming"). Exported as @superset/ui/chat-composer.

  2. Suggestion layer: typing @ opens a mention popover (any position, token charset supports file paths); typing / opens a command popover (message start only). Consumers pass mentions / commands as {id, label, description?, icon?} arrays — filtering is case-insensitive contains, capped at 8.

Interaction details

  • Popover anchors above the composer; ArrowUp/Down cycle (wrapping), Enter/Tab accept, Escape dismisses for the current token (reopens on a new token), mouse hover + click work with focus retained.
  • While the popover is open, Enter accepts instead of submitting — verified that accepting never sends the message.
  • Accepting replaces the active token with @label / /label and restores the caret after the insertion.
  • Token tracking follows the caret (selectionchange via onSelect), so clicking into the middle of @partial reopens the correct query; blur closes the popover.

Verification

Typecheck, Biome, and sherif pass. CDP-verified in Storybook: @Chat → 3 filtered file options with icons; ArrowDown+Enter inserted the second path without submitting; /re → /review with description; Enter completed the command, second Enter submitted and flipped the send button to stop.

https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY


Summary by cubic

Replaces the old textarea composer with a production PromptInput in @superset/chat-ui, adding @mentions, /commands, rich attachments, dictation with Escape-to-cancel, a layout ComposerDropZone, and a ScrollToBottomButton. Menus are docked and ranked, and submit payloads now include structured mentions and attachments.

  • New Features

    • PromptInput: provider-based @ mentions with sectioned, docked menus (top/bottom) and highlight callbacks; ranked / commands that execute actions and only trigger when the token is the full message; structured mentions in submit payloads.
    • Attachments and chips: drag/drop/paste; image/video thumbnails and MIME-aware icons; managed object URLs; onAttachmentClick and onChipClick; single chip renderer with icon slot and blended colors.
    • Dictation: mic with live waveform/timer; send/plus disabled while recording; stop inserts transcript at end; Escape cancels or discards failed transcription with retry; start errors via dictation.onError; editor starts two lines tall.
    • Layout and UX: ComposerDropZone routes drops to the active composer; + opens the @ menu in browse mode; menus are mutually exclusive; ScrollToBottomButton. Storybook scans @superset/chat-ui for Tailwind and imports shadcn/tailwind.css; demos include dictation error/retry and a circular scroll button.
  • Bug Fixes

    • Docked full-width suggestion panels with inner scroll-fade to avoid clipped/offscreen popovers; consistent dismissal on Escape/outside press; fixed double-Escape by making modes exclusive.
    • Attachments: deduped editor vs card drops; video thumbnails; image decode fallback to file card; improved remove badge contrast; chips always present an interactive hover.
    • Mention chips: suppressed native text selection; click selects; Backspace/Delete remove; clicks bubble via onChipClick.
    • Cleanup: removed the superseded textarea composer from @superset/ui; co-located RemoveButton; removed unused formatBytes util and a stray cn import; sidebar story updated to use the circular scroll-to-bottom button.

Written for commit c348fb0. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features

    • Added rich chat composers with text editing, mentions, slash commands, file attachments, drag-and-drop, paste support, attachment previews, and streaming controls.
    • Added Lexical- and Tiptap-based composer options with configurable submission, stopping, placeholders, and auto-resizing behavior.
    • Exposed composer components for reuse across the UI package.
  • Documentation

    • Added interactive Storybook examples covering default, streaming, minimal, and editor-specific scenarios.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds ChatComposer, TiptapComposer, and LexicalComposer. They support suggestions, attachments, submission, streaming controls, public exports, package configuration, editor styling, and Storybook stories.

Changes

Chat composer components

Layer / File(s) Summary
Chat UI package and Storybook wiring
packages/chat-ui/package.json, packages/chat-ui/tsconfig.json, packages/ui/.storybook/main.ts
Adds package metadata, dependencies, TypeScript settings, and Storybook discovery for shared composer stories.
ChatComposer behavior and interaction
packages/ui/src/components/ChatComposer/*, packages/ui/package.json
Adds controlled and uncontrolled input, suggestions, keyboard handling, auto-sizing, attachments, submission, streaming controls, public exports, and Storybook variants.
TiptapComposer editor integration
packages/chat-ui/src/components/TiptapComposer/*
Adds Tiptap editing, mention and command suggestions, file ingestion, submission, streaming controls, styling, exports, and an interactive story.
LexicalComposer editor integration
packages/chat-ui/src/components/LexicalComposer/*
Adds Lexical editing, serialized mention chips, typeahead menus, file ingestion, submission, streaming controls, styling, exports, utilities, and an interactive story.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant Composer
  participant SuggestionMenu
  participant SubmitCallback
  User->>Composer: Enter text or trigger a suggestion
  Composer->>SuggestionMenu: Render filtered mentions or commands
  User->>SuggestionMenu: Select an option
  SuggestionMenu->>Composer: Insert suggestion content
  User->>Composer: Submit text and attachments
  Composer->>SubmitCallback: Send submission payload
Loading

Possibly related PRs

  • superset-sh/superset#5581: Adds related chat composer components with submission, attachments, suggestions, and streaming controls.
  • superset-sh/superset#5758: Adds rich chat composers with attachments, slash-command suggestions, streaming controls, and Tiptap editing.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the primary change by identifying the UI feature and its @mention and /command suggestion support.
Description check ✅ Passed The description explains the changes and provides detailed verification results, although it does not include the required checklist section.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chat-composer-suggestions

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR adds and exports a reusable ChatComposer with auto-growing input, submission and streaming controls, keyboard focus handling, and configurable toolbar and attachment actions. It also adds filtered mention and command suggestions with keyboard and mouse selection.

  • Adds the @superset/ui/chat-composer package export.
  • Implements mention and command token detection, filtering, navigation, dismissal, and insertion.
  • Adds Storybook variants for default, streaming, and minimal composer states.

Confidence Score: 4/5

The PR should not merge until token replacement, IME-safe suggestion acceptance, and controlled-value resizing are corrected.

Mid-token selection preserves stale token suffixes, composition-confirming Enter can accept suggestions unexpectedly, and parent-driven controlled values do not update the textarea's auto-grown height.

Files Needing Attention: packages/ui/src/components/ChatComposer/ChatComposer.tsx

Important Files Changed

Filename Overview
packages/ui/src/components/ChatComposer/ChatComposer.tsx Adds the complete composer and suggestion behavior, but mid-token replacement, IME handling, and controlled resizing contain reachable defects.
packages/ui/src/components/ChatComposer/ChatComposer.stories.tsx Adds representative Storybook states and suggestion data without introducing an independent defect.
packages/ui/package.json Exposes the new component through the package export map.
packages/ui/src/components/ChatComposer/index.ts Re-exports the component and its public TypeScript types.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  Input[Textarea input or caret movement] --> Detect[Detect active @mention or /command token]
  Detect --> Filter[Filter and cap suggestions]
  Filter --> Popover[Render suggestion popover]
  Popover --> Navigate[Arrow keys or mouse select]
  Navigate --> Accept[Enter, Tab, or click accepts]
  Accept --> Replace[Replace active token and restore caret]
  Input --> Submit{Enter submit?}
  Submit -->|Ready and nonempty| OnSubmit[Invoke onSubmit]
  Submit -->|Streaming| Stop[Expose stop action]
Loading
Prompt To Fix All With AI
### Issue 1
packages/ui/src/components/ChatComposer/ChatComposer.tsx:65
**Token replacement stops at caret**

When the caret is moved into an existing mention or command, `activeTokenAt` sets the token end to the caret, so accepting a suggestion preserves the old suffix and produces malformed text such as `/new view` instead of replacing `/review`.

### Issue 2
packages/ui/src/components/ChatComposer/ChatComposer.tsx:211-217
**Suggestion acceptance bypasses IME guard**

When an IME user presses Enter to confirm composed text while suggestions are open, this branch accepts the highlighted suggestion before `isEnterSubmit` can reject the composing event, interrupting composition and inserting an unintended suggestion.

### Issue 3
packages/ui/src/components/ChatComposer/ChatComposer.tsx:165-170
**Controlled updates retain stale height**

When a controlled consumer programmatically replaces `value` with longer or multiline content, this mount-only effect does not rerun and the local `onChange` handler is not invoked, leaving the textarea at its previous height and clipping the new content.

```suggestion
	useLayoutEffect(() => {
		const textarea = textareaRef.current;
		if (!textarea) return;
		textarea.style.height = "auto";
		textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_HEIGHT)}px`;
	}, [value]);
```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "feat(ui): add @mention and /command sugg..." | Re-trigger Greptile

return {
kind: trigger === "@" ? "mention" : "command",
start,
end: caret,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Token replacement stops at caret

When the caret is moved into an existing mention or command, activeTokenAt sets the token end to the caret, so accepting a suggestion preserves the old suffix and produces malformed text such as /new view instead of replacing /review.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/ui/src/components/ChatComposer/ChatComposer.tsx
Line: 65

Comment:
**Token replacement stops at caret**

When the caret is moved into an existing mention or command, `activeTokenAt` sets the token end to the caret, so accepting a suggestion preserves the old suffix and produces malformed text such as `/new view` instead of replacing `/review`.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +211 to +217
if (event.key === "Enter" || event.key === "Tab") {
const item = suggestions[activeIndex];
if (item) {
event.preventDefault();
acceptSuggestion(item);
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Suggestion acceptance bypasses IME guard

When an IME user presses Enter to confirm composed text while suggestions are open, this branch accepts the highlighted suggestion before isEnterSubmit can reject the composing event, interrupting composition and inserting an unintended suggestion.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/ui/src/components/ChatComposer/ChatComposer.tsx
Line: 211-217

Comment:
**Suggestion acceptance bypasses IME guard**

When an IME user presses Enter to confirm composed text while suggestions are open, this branch accepts the highlighted suggestion before `isEnterSubmit` can reject the composing event, interrupting composition and inserting an unintended suggestion.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +165 to +170
useLayoutEffect(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.style.height = "auto";
textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_HEIGHT)}px`;
}, []);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Controlled updates retain stale height

When a controlled consumer programmatically replaces value with longer or multiline content, this mount-only effect does not rerun and the local onChange handler is not invoked, leaving the textarea at its previous height and clipping the new content.

Suggested change
useLayoutEffect(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.style.height = "auto";
textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_HEIGHT)}px`;
}, []);
useLayoutEffect(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.style.height = "auto";
textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_HEIGHT)}px`;
}, [value]);
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/ui/src/components/ChatComposer/ChatComposer.tsx
Line: 165-170

Comment:
**Controlled updates retain stale height**

When a controlled consumer programmatically replaces `value` with longer or multiline content, this mount-only effect does not rerun and the local `onChange` handler is not invoked, leaving the textarea at its previous height and clipping the new content.

```suggestion
	useLayoutEffect(() => {
		const textarea = textareaRef.current;
		if (!textarea) return;
		textarea.style.height = "auto";
		textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_HEIGHT)}px`;
	}, [value]);
```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (1)
packages/ui/src/components/ChatComposer/ChatComposer.stories.tsx (1)

58-170: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Split the local components into co-located component files.

ToolbarButton, DemoToolbar, and ComposerPlayground are separate components in this file. Move each component to its own ComponentName/ComponentName.tsx file with an index.ts barrel export.

As per coding guidelines, **/*.{tsx,ts} requires “Use one folder per component, with ComponentName/ComponentName.tsx and an index.ts barrel export” and “Use one component per file.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ui/src/components/ChatComposer/ChatComposer.stories.tsx` around
lines 58 - 170, Split ToolbarButton, DemoToolbar, and ComposerPlayground into
separate co-located component folders, each containing a ComponentName.tsx
implementation and an index.ts barrel export. Update ChatComposer.stories.tsx to
import and use these exported components, preserving their existing props,
state, behavior, and story wiring.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/ui/src/components/ChatComposer/ChatComposer.tsx`:
- Around line 330-338: Update the streaming Stop button in ChatComposer to be
disabled when the optional onStop handler is undefined, preserving the existing
enabled behavior when a handler is provided.
- Around line 245-266: Update the ChatComposer textarea and suggestion list
accessibility wiring: assign the listbox a stable id, reference it from the
textarea with aria-controls, expose whether suggestions are open through
aria-expanded, and set aria-activedescendant to the active option’s stable id.
Add matching ids to the option elements while preserving the existing keyboard
navigation and selection behavior.
- Around line 54-67: Update activeTokenAt to scan forward from caret to the end
of the current token, allowing the existing token characters (including word,
dot, slash, and hyphen characters), and set the returned end to that boundary
instead of caret. Preserve the current start, query, trigger handling, and null
behavior.
- Around line 165-170: Update the layout effect that adjusts textareaRef height
to rerun when the controlled text value changes, rather than only on mount. Add
the appropriate controlled value dependency while preserving the existing
auto-reset and MAX_HEIGHT clamping behavior.
- Around line 211-216: Update the suggestion acceptance condition in the
ChatComposer key handler to allow Enter only when isEnterSubmit(event) is true,
while preserving Tab acceptance. This prevents acceptance during IME composition
and on Shift+Enter; keep the existing preventDefault, acceptSuggestion, and
return behavior unchanged.

---

Nitpick comments:
In `@packages/ui/src/components/ChatComposer/ChatComposer.stories.tsx`:
- Around line 58-170: Split ToolbarButton, DemoToolbar, and ComposerPlayground
into separate co-located component folders, each containing a ComponentName.tsx
implementation and an index.ts barrel export. Update ChatComposer.stories.tsx to
import and use these exported components, preserving their existing props,
state, behavior, and story wiring.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 770a983f-b87e-4928-9ba0-52d2185eefa6

📥 Commits

Reviewing files that changed from the base of the PR and between c920d52 and 56d4ec1.

📒 Files selected for processing (4)
  • packages/ui/package.json
  • packages/ui/src/components/ChatComposer/ChatComposer.stories.tsx
  • packages/ui/src/components/ChatComposer/ChatComposer.tsx
  • packages/ui/src/components/ChatComposer/index.ts

Comment on lines +165 to +170
useLayoutEffect(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.style.height = "auto";
textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_HEIGHT)}px`;
}, []);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
git ls-files | rg '(^|/)packages/ui/src/components/ChatComposer/ChatComposer\.tsx$|ChatComposer' || true

echo "== file outline =="
ast-grep outline packages/ui/src/components/ChatComposer/ChatComposer.tsx --view compact || true

echo "== relevant ChatComposer lines =="
cat -n packages/ui/src/components/ChatComposer/ChatComposer.tsx | sed -n '1,260p'

echo "== usages/parent value sources =="
rg -n "ChatComposer|onSubmit|setValue|clear|draft|Textarea|handle.*Chat|message" packages -g '*.{ts,tsx,js,jsx}' | head -n 220

Repository: superset-sh/superset

Length of output: 32695


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== ChatComposer remaining lines =="
cat -n packages/ui/src/components/ChatComposer/ChatComposer.tsx | sed -n '260,420p'

echo "== ChatComposer refs/usages =="
rg -n "ChatComposer\(" packages/ui apps -g '*.{ts,tsx}' || true

echo "== all ChatComposer usages in relevant UI/desktop/mobile =="
rg -n "ChatComposer\(" . -g '*.{ts,tsx}' || true

echo "== exact textarea resize dependency occurrences =="
rg -n "style\.height|scrollHeight|useLayoutEffect|pendingCaret|controlledValue" packages/ui/src/components/ChatComposer packages/ui/src/components packages -g '*.{ts,tsx}' || true

echo "== textual diff/stat if available =="
git diff -- packages/ui/src/components/ChatComposer/ChatComposer.tsx | sed -n '1,220p' || true

Repository: superset-sh/superset

Length of output: 12634


Resize controlled value changes.

The mount-only layout effect cannot reset height when a parent switches value after submission or loads a draft. Add value to this effect’s dependency, or resize from a controlled-value effect when controlledValue is supplied.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ui/src/components/ChatComposer/ChatComposer.tsx` around lines 165 -
170, Update the layout effect that adjusts textareaRef height to rerun when the
controlled text value changes, rather than only on mount. Add the appropriate
controlled value dependency while preserving the existing auto-reset and
MAX_HEIGHT clamping behavior.

Comment on lines +245 to +266
<div
ref={suggestionListRef}
role="listbox"
aria-label={token.kind === "mention" ? "Mentions" : "Commands"}
className="absolute bottom-full left-3 z-50 mb-2 max-h-72 w-80 max-w-[calc(100%-1.5rem)] overflow-y-auto rounded-xl bg-popover/95 p-1 shadow-xl ring-1 ring-border backdrop-blur-sm"
>
{suggestions.map((item, index) => (
// biome-ignore lint/a11y/useKeyWithClickEvents: keyboard handled by the textarea (arrows + enter)
<div
key={item.id}
role="option"
aria-selected={index === activeIndex}
data-highlighted={index === activeIndex || undefined}
className={cn(
"flex cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-sm",
index === activeIndex
? "bg-accent text-accent-foreground"
: "text-foreground",
)}
onMouseEnter={() => setHighlight(index)}
onMouseDown={(event) => event.preventDefault()}
onClick={() => acceptSuggestion(item)}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and inspect the relevant component and nearby focus/aria behavior.
if [ -f packages/ui/src/components/ChatComposer/ChatComposer.tsx ]; then
  echo "FILE_EXISTS"
  wc -l packages/ui/src/components/ChatComposer/ChatComposer.tsx
  ast-grep outline packages/ui/src/components/ChatComposer/ChatComposer.tsx || true
  echo "---- aria/focus/textarea refs ----"
  rg -n "aria-expanded|aria-controls|aria-activedescendant|suggestionListRef|suggestions|setActive|activeIndex|textarea|ref=|role=\"listbox\"|role=\"option\"" packages/ui/src/components/ChatComposer/ChatComposer.tsx
  echo "---- relevant source around textarea/listbox ----"
  sed -n '180,310p' packages/ui/src/components/ChatComposer/ChatComposer.tsx | cat -n
else
  echo "FILE_NOT_FOUND"
  fd -a 'ChatComposer\.tsx$' .
fi

Repository: superset-sh/superset

Length of output: 8085


Connect the suggestion list to the textarea via ARIA.

The textarea keeps focus while keyboard navigation controls this listbox/option. Add a stable ID from the textarea to the aria-activedescendant, a listbox id from aria-controls, and aria-expanded when suggestions are open.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ui/src/components/ChatComposer/ChatComposer.tsx` around lines 245 -
266, Update the ChatComposer textarea and suggestion list accessibility wiring:
assign the listbox a stable id, reference it from the textarea with
aria-controls, expose whether suggestions are open through aria-expanded, and
set aria-activedescendant to the active option’s stable id. Add matching ids to
the option elements while preserving the existing keyboard navigation and
selection behavior.

Comment on lines +330 to +338
{status === "streaming" ? (
<button
type="button"
aria-label="Stop response"
onClick={onStop}
className="flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg bg-secondary text-secondary-foreground transition-colors hover:bg-secondary/80"
>
<SquareIcon className="size-3.5 fill-current" />
</button>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Disable Stop when no stop handler exists.

onStop is optional, but this branch renders an enabled Stop button when it is absent. packages/ui/src/components/ChatComposer/ChatComposer.stories.tsx Lines 176-185 exercise that no-op state. Disable the button when onStop is undefined, or require onStop for streaming usage.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ui/src/components/ChatComposer/ChatComposer.tsx` around lines 330 -
338, Update the streaming Stop button in ChatComposer to be disabled when the
optional onStop handler is undefined, preserving the existing enabled behavior
when a handler is provided.

@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ✅ Neon database branch

Thank you for your contribution! 🎉

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (7)
packages/chat-ui/src/components/ComposerEditor/ComposerEditor.stories.tsx (1)

44-98: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move each component to its own component directory.

This story defines both Harness and BakeOff in one file. Move each component to ComponentName/ComponentName.tsx and add an index.ts barrel export. Keep the story file focused on Storybook metadata and the story definition.

As per coding guidelines, “Use one component per file and organize components as ComponentName/ComponentName.tsx with an index.ts barrel export.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/ComposerEditor.stories.tsx`
around lines 44 - 98, Split the story-local Harness and BakeOff components into
separate Harness/Harness.tsx and BakeOff/BakeOff.tsx files, each with an
index.ts barrel export. Update the story to import both components and retain
only Storybook metadata and the story definition, preserving their existing
props, state, and rendering behavior.

Source: Coding guidelines

packages/chat-ui/package.json (1)

40-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Relax the React peer range and declare react-dom.

An exact peer pin of 19.2.3 forces every consumer to that patch version and causes install conflicts when the app bumps React. Use a caret range instead. The package renders through @lexical/react and @tiptap/react, so react-dom also belongs in peerDependencies.

♻️ Proposed change
 	"peerDependencies": {
-		"react": "19.2.3"
+		"react": "^19.2.0",
+		"react-dom": "^19.2.0"
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/package.json` around lines 40 - 42, Update the
peerDependencies entry for react to use a caret range compatible with 19.2.3,
and add react-dom as a peer dependency alongside it for the package’s rendering
integrations.
packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx (1)

317-323: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Rethrowing in onError escalates every Lexical error to a crash.

Lexical calls onError for recoverable reconciliation errors. Rethrowing unmounts the composer through the nearest error boundary and loses the user's draft. Log the error and report it, then let the editor continue.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx`
around lines 317 - 323, Update the LexicalComposerEditor initialConfig onError
handler to stop rethrowing errors; log the received error and send it through
the existing error-reporting mechanism, allowing the editor to continue without
unmounting or losing the draft.
packages/chat-ui/src/components/ComposerEditor/index.ts (1)

10-13: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move ComposerEditorProps out of TiptapComposerEditor.tsx.

LexicalComposerEditor.tsx imports ComposerEditorProps from TiptapComposerEditor (line 39 of that file). That makes the Lexical implementation depend on the Tiptap module for a shared contract. Declare the shared props type in composerLogic.ts, then import it in both editors and re-export it here.

♻️ Proposed change

composerLogic.ts:

+export type ComposerEditorProps = {
+	placeholder?: string;
+	mentionItems: ComposerMentionItem[];
+	onSubmit?: (text: string) => void;
+	onTextChange?: (text: string) => void;
+	className?: string;
+};

index.ts:

 export {
 	type ComposerChipKind,
+	type ComposerEditorProps,
 	type ComposerMentionItem,
 	type ComposerTrigger,
 	detectComposerTrigger,
 	filterMentionItems,
 	serializeChip,
 } from "./composerLogic";
 export { LexicalComposerEditor } from "./LexicalComposerEditor";
-export {
-	type ComposerEditorProps,
-	TiptapComposerEditor,
-} from "./TiptapComposerEditor";
+export { TiptapComposerEditor } from "./TiptapComposerEditor";

Based on learnings: as per coding guidelines, "Co-locate components, utilities, hooks, constants, configuration, tests, and stories with the code that uses them; promote components shared by two or more consumers to the highest shared parent."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/index.ts` around lines 10 -
13, Move the shared ComposerEditorProps declaration from
TiptapComposerEditor.tsx into composerLogic.ts, then update both
TiptapComposerEditor and LexicalComposerEditor to import it from composerLogic.
Keep the existing re-export from the package index so consumers continue
importing ComposerEditorProps through the public entry point.

Source: Coding guidelines

packages/chat-ui/src/components/ComposerEditor/TiptapComposerEditor.tsx (2)

88-88: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

The placeholder prop is captured once.

useState runs the initializer only on the first render, so Placeholder.configure({ placeholder }) keeps the initial value. A later placeholder prop change has no effect. If the prop is expected to stay constant, document that constraint. Otherwise, update the extension option when the prop changes.

Also applies to: 155-155

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/TiptapComposerEditor.tsx` at
line 88, Update the extension initialization around the ComposerEditor
component’s useState so changes to the placeholder prop are reflected in
Placeholder.configure instead of retaining only the initial value;
alternatively, explicitly document that placeholder must remain constant if that
is the intended contract.

159-175: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use Extension.create for behavior-only Tiptap extensions.

composerSubmit, composerSuggestionFile, and composerSuggestionSkill do not define schema content or render attributes, and neither factory is used as an insertable node command. Register them with Extension.create instead of Node.create so the schema only contains composerChip as a node type.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/TiptapComposerEditor.tsx`
around lines 159 - 175, Replace the behavior-only `Node.create` factories for
`composerSubmit`, `composerSuggestionFile`, and `composerSuggestionSkill` with
`Extension.create`, preserving their existing keyboard shortcuts and suggestion
behavior so only `composerChip` remains registered as a schema node.
packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx (1)

22-32: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Wire the listbox to the editor for assistive technology.

Focus stays in the editor, so a screen reader never reports the highlighted option. aria-selected alone does not announce the change. Give each option a stable id, then set aria-activedescendant, aria-controls, and aria-expanded on the editor element.

Add an id prop and per-option ids here, and pass the matching attributes from TiptapComposerEditor and LexicalComposerEditor.

♻️ Proposed change
 export type SuggestionPopoverProps = {
+	id: string;
 	items: ComposerMentionItem[];
 	activeIndex: number;
 	onHighlight: (index: number) => void;
 	onSelect: (item: ComposerMentionItem) => void;
 };
 		<div
 			role="listbox"
+			id={id}
 			className="absolute bottom-full left-0 z-50 mb-2 max-h-72 w-80 overflow-y-auto rounded-xl bg-popover/95 p-1 shadow-xl ring-1 ring-border backdrop-blur-sm"
 		>
 			{items.map((item, index) => (
 				<div
 					key={item.id}
+					id={`${id}-option-${index}`}
 					role="option"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx` around
lines 22 - 32, Update SuggestionPopover and its editor integration: add an id
prop to the popover, assign stable unique ids to each option, and expose the
popover id plus matching aria-activedescendant, aria-controls, and aria-expanded
attributes on the editor elements in TiptapComposerEditor and
LexicalComposerEditor. Preserve the existing activeIndex selection behavior and
ensure the active descendant references the corresponding option id.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx`:
- Around line 209-218: Clamp activeIndex in the suggestion update flow after
filtering items, ensuring it does not exceed items.length - 1 when the list
shrinks while trigger.rangeStart remains unchanged. Update the setActiveIndex
logic in the visible suggestion-handling block, preserving the reset to 0 when
the trigger range changes and the existing empty-list behavior.
- Around line 116-120: Update the inline style cast in the ComposerEditor
component to use an explicit type-only import of CSSProperties from react,
replacing the React.CSSProperties namespace reference with CSSProperties while
preserving the existing --chip-color style behavior.

In `@packages/chat-ui/src/components/ComposerEditor/TiptapComposerEditor.tsx`:
- Around line 101-141: The suggestion state in TiptapComposerEditor must keep
activeIndex valid: reject empty props.items in both onStart and onUpdate, and
return false from onKeyDown when count is zero before modulo or item access. In
packages/chat-ui/src/components/ComposerEditor/TiptapComposerEditor.tsx lines
101-141, apply these changes. In
packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx lines
209-218, clamp the retained active index with Math.min(previous, items.length -
1) when trigger.rangeStart is unchanged and the items array shrinks.

---

Nitpick comments:
In `@packages/chat-ui/package.json`:
- Around line 40-42: Update the peerDependencies entry for react to use a caret
range compatible with 19.2.3, and add react-dom as a peer dependency alongside
it for the package’s rendering integrations.

In `@packages/chat-ui/src/components/ComposerEditor/ComposerEditor.stories.tsx`:
- Around line 44-98: Split the story-local Harness and BakeOff components into
separate Harness/Harness.tsx and BakeOff/BakeOff.tsx files, each with an
index.ts barrel export. Update the story to import both components and retain
only Storybook metadata and the story definition, preserving their existing
props, state, and rendering behavior.

In `@packages/chat-ui/src/components/ComposerEditor/index.ts`:
- Around line 10-13: Move the shared ComposerEditorProps declaration from
TiptapComposerEditor.tsx into composerLogic.ts, then update both
TiptapComposerEditor and LexicalComposerEditor to import it from composerLogic.
Keep the existing re-export from the package index so consumers continue
importing ComposerEditorProps through the public entry point.

In `@packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx`:
- Around line 317-323: Update the LexicalComposerEditor initialConfig onError
handler to stop rethrowing errors; log the received error and send it through
the existing error-reporting mechanism, allowing the editor to continue without
unmounting or losing the draft.

In `@packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx`:
- Around line 22-32: Update SuggestionPopover and its editor integration: add an
id prop to the popover, assign stable unique ids to each option, and expose the
popover id plus matching aria-activedescendant, aria-controls, and aria-expanded
attributes on the editor elements in TiptapComposerEditor and
LexicalComposerEditor. Preserve the existing activeIndex selection behavior and
ensure the active descendant references the corresponding option id.

In `@packages/chat-ui/src/components/ComposerEditor/TiptapComposerEditor.tsx`:
- Line 88: Update the extension initialization around the ComposerEditor
component’s useState so changes to the placeholder prop are reflected in
Placeholder.configure instead of retaining only the initial value;
alternatively, explicitly document that placeholder must remain constant if that
is the intended contract.
- Around line 159-175: Replace the behavior-only `Node.create` factories for
`composerSubmit`, `composerSuggestionFile`, and `composerSuggestionSkill` with
`Extension.create`, preserving their existing keyboard shortcuts and suggestion
behavior so only `composerChip` remains registered as a schema node.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 53a601b0-727c-4bd3-95b2-50599371fb64

📥 Commits

Reviewing files that changed from the base of the PR and between 56d4ec1 and 1082e11.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • packages/chat-ui/package.json
  • packages/chat-ui/src/components/ComposerEditor/ComposerEditor.stories.tsx
  • packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx
  • packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx
  • packages/chat-ui/src/components/ComposerEditor/TiptapComposerEditor.tsx
  • packages/chat-ui/src/components/ComposerEditor/composer-chip.css
  • packages/chat-ui/src/components/ComposerEditor/composerLogic.ts
  • packages/chat-ui/src/components/ComposerEditor/index.ts
  • packages/chat-ui/tsconfig.json
  • packages/ui/.storybook/main.ts
  • packages/ui/src/components/ChatComposer/ChatComposer.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/ui/src/components/ChatComposer/ChatComposer.tsx

Comment on lines +116 to +120
style={
this.__brandColor
? ({ "--chip-color": this.__brandColor } as React.CSSProperties)
: undefined
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether the shared base config enables UMD global access
fd -t f 'base.json' | xargs -r -I{} sh -c 'echo "== {} =="; cat {}'
rg -n 'allowUmdGlobalAccess' --glob '*.json' || echo "allowUmdGlobalAccess not set anywhere"

Repository: superset-sh/superset

Length of output: 953


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== tsconfig files =="
fd -t f 'tsconfig.*json|package.json' . | sort

echo "== chat-ui tsconfig =="
fd -t f 'tsconfig.*json' packages/chat-ui -x sh -c 'echo "--- $1"; cat "$1"' sh {}

echo "== package manager and react typings versions =="
fd -t f 'package.json|bun.lockb|pnpm-lock.yaml|yarn.lock|package-lock.json' . | sed -n '1,80p'
echo "--- package.json imports react"
fd -t f 'package.json' . -x sh -c 'echo "--- $1"; grep -n "\"react\"\\|\\\"typescript\\\"\\|\\\"`@types/react`\\\"\\|\\\"`@types/node`\\\"" "$1" | sed -n "1,80p"' sh {}

echo "== target file imports and relevant line =="
sed -n '1,180p' packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx

echo "== TypeScript references for CSSProperties =="
rg -n 'namespace React|interface JSX|CSSProperties|type JSX' --glob '*.d.ts' node_modules/@types 2>/dev/null | sed -n '1,120p' || echo "no matches in node_modules/@types"

Repository: superset-sh/superset

Length of output: 21390


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== package manager files =="
git ls-files | rg '(^|/)bun\.lockb?|(^|/)(\.bun|package(?:-lock)?\.json|pnpm-lock\.yaml|yarn\.lock)$' | sed -n '1,80p'

echo "== lockfile package entries for react/typescript =="
for f in $(git ls-files | rg '(^|/)bun\.lock|(^|/)package\.json|(^|/)metadata\.lock$' | head -20); do
  echo "--- $f"
  rg -n '(^|\s)"react"(\.)?|`@types/react`|typescript|allowUmdGlobalAccess' "$f" | sed -n '1,80p' || true
done

echo "== current React.CSSProperties usages in repo =="
rg -n '\bReact\.(CSSProperties|JSX)|CSSProperties|declare namespace React|namespace React' --glob '*.{ts,tsx,js,jsx,d.ts,json}' . | sed -n '1,120p'

Repository: superset-sh/superset

Length of output: 11636


🌐 Web query:

TypeScript 6 allowUmdGlobalAccess module namespace imports CSSProperties React namespace

💡 Result:

The allowUmdGlobalAccess compiler option is a long-standing feature in TypeScript, introduced in version 3.5 [1][2]. It allows code within module files (files containing top-level import or export statements) to access UMD-declared global variables without requiring an explicit import declaration [3][4]. Normally, TypeScript restricts access to these globals to maintain module integrity, requiring an import [3][5]. Regarding your specific interests: 1. allowUmdGlobalAccess: This flag is intended as an "escape hatch" for legacy scenarios where a library is guaranteed to be available globally at runtime but cannot be easily imported [3][2]. While it remains available, it is not recommended for modern module-based development where explicit imports are safer and clearer [5]. Note that TypeScript 6.0 is deprecating several older module systems (like UMD, AMD, and SystemJS) [6], though allowUmdGlobalAccess itself is a distinct configuration option for handling global availability rather than a module resolution strategy. 2. React CSSProperties: This type is part of the React namespace and is used to define the object passed to React's style prop [7][8]. It is effectively a re-import of types from the csstype package [9]. 3. Module Namespace Imports and CSS: React's CSSProperties does not rely on allowUmdGlobalAccess for its standard usage. If you need to extend CSSProperties to support CSS custom properties (variables) or other non-standard attributes, the authoritative approach is to use a declaration merging file (e.g., react-extensions.d.ts) to augment the react module [9][10]: // Example: Extending CSSProperties in a declaration file import "react"; declare module "react" { interface CSSProperties { [key: --${string}]: string | number | undefined | null; } } This allows you to safely use CSS variables in your React components without needing to alter global settings or bypass module boundaries [10].

Citations:


🌐 Web query:

@types/react 19.2.14 index.d.ts React.CSSProperties export import CSSProperties

💡 Result:

In @types/react version 19.2.14, CSSProperties is exported as part of the React namespace [1]. It is defined as a re-export of the Properties interface from the csstype package [2][3]. You can access or import it directly from the React package in your TypeScript code as follows: import { CSSProperties } from 'react'; // or import type * as React from 'react'; const style: React.CSSProperties = { color: 'red' }; The definition relies on the csstype library, which provides comprehensive TypeScript definitions for CSS properties [4][3]. Because CSSProperties is an alias for csstype's Properties, custom CSS variable support (such as keys starting with --) is generally managed by extending the CSSProperties interface in your own declaration files if needed, as it is not explicitly enabled in the default exported type [5][3].

Citations:


🌐 Web query:

TypeScript allowUmdGlobalAccess import module namespace UMD declaration file TypeScript 6

💡 Result:

The allowUmdGlobalAccess compiler option is a feature in TypeScript (introduced in version 3.5) designed to act as an escape hatch for scenarios where UMD (Universal Module Definition) libraries must be accessed as globals from within module files [1][2]. By default, TypeScript prevents code in a module file (any file containing top-level import or export statements) from accessing global variables, including those exposed by UMD libraries [1][3]. This is an intentional safeguard to ensure explicit dependencies and maintain type safety, as the global variable may not be available if the code is executed in a different runtime environment [2][4]. When "allowUmdGlobalAccess": true is enabled in your tsconfig.json: 1. TypeScript will suppress the diagnostic error (TS2686) that typically occurs when referencing a UMD global from a module file [1][2]. 2. You can directly access the library's namespace or export as a global variable without needing an explicit import statement [1][4]. This flag is primarily intended for legacy projects or environments (such as specific browser-based setups) where certain libraries are guaranteed to be present on the global scope at runtime but are not or cannot be imported via standard module syntax [1][2]. For standard TypeScript development, it is generally recommended to import UMD libraries using standard import statements (e.g., import * as lib from 'lib') and use their corresponding @types definitions, rather than relying on global access [4]. Regarding UMD declaration files: The syntax export as namespace is used in.d.ts files to inform TypeScript that a module can also be accessed as a global variable [3]. When this declaration is present, the library functions as a UMD module, and the compiler uses this information to allow global access in non-module files or when allowUmdGlobalAccess is enabled in module files [3][5].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== target imports/exports in LexicalComposerEditor =="
sed -n '1,25p' packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx
echo "== package exports for `@lexical/react` and lexical =="
python3 - <<'PY'
import json
from pathlib import Path
root=Path('.')
for p in ['apps/desktop/package.json','apps/admin/package.json','apps/web/package.json','package.json']:
    if p.exists():
        data=json.loads(Path(p).read_text())
        print(f'--- {p}')
        for section in ['dependencies','devDependencies']:
            if section in data:
                for name in ['`@lexical/react`','lexical']:
                    if name in data[section]:
                        print(f'{section}.{name}={data[section][name]}')
PY

echo "== React UMD namespace declarations in bundled typings, if available =="
python3 - <<'PY'
from pathlib import Path
for p in Path('.').rglob('*`@types`*react*.json'):
    if p.is_file():
        print(p)
PY

Repository: superset-sh/superset

Length of output: 1151


🌐 Web query:

TypeScript 3 module exportAsNamespace "react" allowUmdGlobalAccess

💡 Result:

In TypeScript, export as namespace and allowUmdGlobalAccess are mechanisms designed to manage how libraries written as Universal Module Definitions (UMD) are consumed in different environments [1][2]. export as namespace is a declaration syntax used in type definition (.d.ts) files [3][2]. It allows a UMD module to expose its exports to the global scope under a specified identifier when a module loader is not present (such as when loading a library via a <script> tag in a browser) [1][2][4]. For example, the React type definitions include export as namespace React; so that React is available globally in script contexts [5][4]. By default, TypeScript enforces strict module boundaries [2]. If a file is treated as a module (because it contains a top-level import or export statement), TypeScript will typically throw an error (e.g., TS2686) if you attempt to use a UMD global identifier, requiring you to use a standard import instead [5][2]. The allowUmdGlobalAccess compiler option, introduced in TypeScript 3.5, acts as an "escape hatch" to relax this restriction [6][7][8]. When set to true in your tsconfig.json, it allows you to access UMD exports as globals even from within module files, bypassing the requirement to add an explicit import declaration [9][2][10]. This is useful in scenarios where a library is guaranteed to be available globally at runtime (e.g., injected via a CDN) and you cannot or prefer not to import it via a module system [9][7][10]. To enable this, update your configuration: { "compilerOptions": { "allowUmdGlobalAccess": true } } [9][11]

Citations:


Remove the implicit React namespace access and import the React type instead.

This component is an ES module, and the chat-ui TypeScript config does not enable allowUmdGlobalAccess. Use import type { CSSProperties } from "react" and cast the inline style as CSSProperties.

</verification result>

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx`
around lines 116 - 120, Update the inline style cast in the ComposerEditor
component to use an explicit type-only import of CSSProperties from react,
replacing the React.CSSProperties namespace reference with CSSProperties while
preserving the existing --chip-color style behavior.

Comment on lines +209 to +218
if (items.length === 0) {
setSuggestion(null);
return;
}
setActiveIndex((previous) =>
stateRef.current.suggestion?.trigger.rangeStart !== trigger.rangeStart
? 0
: previous,
);
setSuggestion({ trigger, items, anchorKey: anchorNode.getKey() });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Clamp activeIndex when the filtered items list shrinks.

Line 213 resets activeIndex only when trigger.rangeStart changes. The rangeStart stays constant while the user types more characters of the same token, but items shrinks. activeIndex can then point past the end of items.

The consequence is at line 230: current.suggestion.items[current.activeIndex] returns undefined, the handler falls through, and Enter submits the message with the unresolved @token text while the popover is open.

Clamp the index against the new item count.

🐛 Proposed fix
-				setActiveIndex((previous) =>
-					stateRef.current.suggestion?.trigger.rangeStart !== trigger.rangeStart
-						? 0
-						: previous,
-				);
+				setActiveIndex((previous) =>
+					stateRef.current.suggestion?.trigger.rangeStart !== trigger.rangeStart
+						? 0
+						: Math.min(previous, items.length - 1),
+				);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (items.length === 0) {
setSuggestion(null);
return;
}
setActiveIndex((previous) =>
stateRef.current.suggestion?.trigger.rangeStart !== trigger.rangeStart
? 0
: previous,
);
setSuggestion({ trigger, items, anchorKey: anchorNode.getKey() });
if (items.length === 0) {
setSuggestion(null);
return;
}
setActiveIndex((previous) =>
stateRef.current.suggestion?.trigger.rangeStart !== trigger.rangeStart
? 0
: Math.min(previous, items.length - 1),
);
setSuggestion({ trigger, items, anchorKey: anchorNode.getKey() });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx`
around lines 209 - 218, Clamp activeIndex in the suggestion update flow after
filtering items, ensuring it does not exceed items.length - 1 when the list
shrinks while trigger.rangeStart remains unchanged. Update the setActiveIndex
logic in the visible suggestion-handling block, preserving the reset to 0 when
the trigger range changes and the existing empty-list behavior.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx (1)

40-52: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Expose the active option to assistive technology.

The editor keeps focus in EditorContent, but SuggestionPopover only uses aria-selected on the options; it has no listbox ID and no aria-activedescendant link. Add stable option IDs and connect the popover and active option from the Tiptap and Lexical editor contexts, since the current callers do not pass ID props and add no ARIA linkage.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx` around
lines 40 - 52, Update SuggestionPopover to generate stable IDs for the listbox
and each option, set the popover’s id and aria-activedescendant to the active
option ID, and preserve aria-selected on options. Use the existing Tiptap and
Lexical editor contexts to apply the corresponding aria-activedescendant linkage
to EditorContent, without requiring new caller-provided ID props.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx`:
- Around line 17-22: Move the SuggestionPopover component from its current file
into a SuggestionPopover/SuggestionPopover.tsx directory structure, and add an
index.ts barrel that re-exports it. Update any imports or exports referencing
SuggestionPopover to use the new barrel without changing the component’s
behavior.
- Line 34: Update the placement calculation effect in SuggestionPopover so it
recalculates when the anchor position, viewport dimensions, or popup height
changes, not only when items.length changes. Include the relevant
anchor/viewport and size dependencies, then re-test that side switches when the
current placement becomes clipped.
- Around line 28-33: Update SuggestionPopover’s placement logic to anchor
against the editor trigger element rather than popover.offsetParent. Pass an
explicit trigger element or its DOMRect into SuggestionPopover, and use that
value when calculating fitsAbove; preserve the existing viewport-margin and
above/below side selection behavior.

---

Outside diff comments:
In `@packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx`:
- Around line 40-52: Update SuggestionPopover to generate stable IDs for the
listbox and each option, set the popover’s id and aria-activedescendant to the
active option ID, and preserve aria-selected on options. Use the existing Tiptap
and Lexical editor contexts to apply the corresponding aria-activedescendant
linkage to EditorContent, without requiring new caller-provided ID props.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 930378ee-0963-416c-8367-708a1314e820

📥 Commits

Reviewing files that changed from the base of the PR and between 1082e11 and 3b06d94.

📒 Files selected for processing (1)
  • packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx

Comment on lines +17 to +22
export function SuggestionPopover({
items,
activeIndex,
onHighlight,
onSelect,
}: SuggestionPopoverProps) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Use the required component directory layout.

Move SuggestionPopover to packages/chat-ui/src/components/ComposerEditor/SuggestionPopover/SuggestionPopover.tsx and add packages/chat-ui/src/components/ComposerEditor/SuggestionPopover/index.ts as the barrel export.

As per coding guidelines, use one component per file and organize components as ComponentName/ComponentName.tsx with an index.ts barrel export.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx` around
lines 17 - 22, Move the SuggestionPopover component from its current file into a
SuggestionPopover/SuggestionPopover.tsx directory structure, and add an index.ts
barrel that re-exports it. Update any imports or exports referencing
SuggestionPopover to use the new barrel without changing the component’s
behavior.

Source: Coding guidelines

Comment on lines +28 to +33
const anchor = popover?.offsetParent;
if (!popover || !anchor) return;
const anchorRect = anchor.getBoundingClientRect();
const fitsAbove =
anchorRect.top - popover.offsetHeight - VIEWPORT_MARGIN >= 0;
setSide(fitsAbove ? "above" : "below");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 12 \
  'SuggestionPopover|offsetParent|getBoundingClientRect|top-full|bottom-full' \
  packages/chat-ui/src/components/ComposerEditor --glob '*.{ts,tsx}'

Repository: superset-sh/superset

Length of output: 15897


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- SuggestionPopover props and implementation ---\n'
sed -n '1,90p' packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx

printf '\n--- Tiptap caller area ---\n'
sed -n '190,225p' packages/chat-ui/src/components/ComposerEditor/TiptapComposerEditor.tsx

printf '\n--- Lexical caller outline and relevant area ---\n'
ast-grep outline packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx --view condensed || true
sed -n '250,310p' packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx

printf '\n--- CSS positioning references ---\n'
rg -n '\brelative\b|position:\s*relative|left-0|absolute' packages/chat-ui/src/components/ComposerEditor --glob '*.css' --glob '*.tsx'

Repository: superset-sh/superset

Length of output: 249


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- SuggestionPopover props and implementation ---'
sed -n '1,90p' packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx

printf '%s\n' ''
printf '%s\n' '--- Tiptap caller area ---'
sed -n '190,225p' packages/chat-ui/src/components/ComposerEditor/TiptapComposerEditor.tsx

printf '%s\n' ''
printf '%s\n' '--- Lexical caller relevant area ---'
sed -n '250,310p' packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx

printf '%s\n' ''
printf '%s\n' '--- CSS positioning references ---'
rg -n '\brelative\b|position:\s*relative|left-0|absolute' packages/chat-ui/src/components/ComposerEditor --glob '*.css' --glob '*.tsx'

Repository: superset-sh/superset

Length of output: 5529


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- LexicalComposerEditor wrapper and JSX ---'
sed -n '300,345p' packages/chat-ui/src/components/ComposerEditor/LexicalComposerEditor.tsx

printf '%s\n' ''
printf '%s\n' '--- Check SuggestionPopover usage outside ComposerEditor (if any) ---'
rg -n 'SuggestionPopover\s*\(' --glob '*.{ts,tsx}' | sed 's#^packages/chat-ui/src/#packages/chat-ui/src/#'

Repository: superset-sh/superset

Length of output: 1376


Anchor SuggestionPopover to the editor trigger element.

The popover is sibling to EditorContent, and offsetParent is the nearest positioned ancestor, so it can use the editor frame rectangle instead of the caret/trigger rectangle. Make the anchor or rectangle an explicit prop, or compute placement outside the popover using the trigger element.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx` around
lines 28 - 33, Update SuggestionPopover’s placement logic to anchor against the
editor trigger element rather than popover.offsetParent. Pass an explicit
trigger element or its DOMRect into SuggestionPopover, and use that value when
calculating fitsAbove; preserve the existing viewport-margin and above/below
side selection behavior.

const fitsAbove =
anchorRect.top - popover.offsetHeight - VIEWPORT_MARGIN >= 0;
setSide(fitsAbove ? "above" : "below");
}, [items.length]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 8 \
  'useLayoutEffect|items\.length|ResizeObserver|resize|scroll' \
  packages/chat-ui/src/components/ComposerEditor --glob '*.{ts,tsx}'

Repository: superset-sh/superset

Length of output: 9660


🏁 Script executed:

#!/bin/bash
set -euo pipefail

cat -n packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx
printf '\n--- nearby usages ---\n'
rg -n -C 4 'SuggestionPopover' packages/chat-ui/src/components/ComposerEditor --glob '*.{ts,tsx}'
printf '\n--- focused placement/dom mutation search ---\nMentionPopup'
rg -n -C 6 'popper|placement|compute|position|rect|rangeStart|range' packages/chat-ui/src/components/ComposerEditor --glob '*.{ts,tsx}'

Repository: superset-sh/superset

Length of output: 23758


Recalculate popover placement when anchor or viewport changes.

side only updates when items.length changes, but anchor/viewport or popup height changes can make the current side clipped. Recalculate placement from the actual anchor/viewport changes and re-test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/chat-ui/src/components/ComposerEditor/SuggestionPopover.tsx` at line
34, Update the placement calculation effect in SuggestionPopover so it
recalculates when the anchor position, viewport dimensions, or popup height
changes, not only when items.length changes. Include the relevant
anchor/viewport and size dependencies, then re-test that side switches when the
current placement becomes clipped.

All chips render through one component: an icon slot pinned to the
first text line, a wrapping label with a dashed underline on hover,
and a color stack that mixes the chip color toward the foreground
(80/20 srgb base, 50/50 oklch in dark mode) so brand colors stay
legible on dark backgrounds. Icons are carried as URL strings on the
chip payload, keeping chips pure serializable data; the example wires
favicons for plugin chips and preset icons for workspace and
conversation chips.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
Scrollable menu content now fades at the overflowing edges using the
shadcn scroll-fade utility (mask-image driven by CSS scroll-driven
animations, no JS). The utility ships in the shadcn package's
tailwind.css, imported by the Storybook CSS pipeline; consuming apps
need the same import for the fade to apply.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
Masking the card itself faded out its background, ring, and rounded
top edge along with the content, so scrolling looked like the menu was
dissolving. The fade now lives on an inner scroll container: content
fades against the card background while the chrome stays crisp.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
Dictation: a mic button appears when the app supplies a transcribe
callback. Recording swaps the toolbar row for a live waveform strip
(canvas bars on a midline, silence floors to dots, pre-speech bars
dimmed) with an elapsed timer; the + and send buttons stay in place
but disabled, keeping every button its normal shape. Stop ends the
recording and inserts the transcript at the end of the message. Audio
capture is MediaRecorder + AnalyserNode; speech-to-text stays
app-owned.

The slash menu now shares the mention menu's dismissal behavior:
an outside press dismisses it and refocusing the same token keeps it
closed until the query changes. The editor also starts three lines
tall instead of one.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
The textarea-based ChatComposer in packages/ui is superseded by
chat-ui's LexicalComposer and had no consumers; its package export is
gone too. The automation form story duplicated composer coverage.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
The timer had 12px on its left but the buttons packed at 4px with an
extra stray pad on the waveform. The whole row now uses one 12px gap
in both idle and recording states.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
The waveform now left-pads with silence dots so the whole track is
visible from the first frame, with new bars entering at the right
edge. The bar buffer also no longer loses audio on slow frames: the
catch-up loop pushed the measured peak once and then filled every
remaining missed interval with silence, which read as random chunks
vanishing mid-speech; all missed bars now carry the measured peak.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
Recording auto-starts dictation against a synthesized WebAudio mic
stub (no permission prompt, speech-like bursts), BrowseMenu opens the
+ menu, and WithAttachments drops an image plus a file card via play
functions on a minimal composer scaffold.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
Clickable attachment chips fade in a subtle foreground overlay on
hover (replacing the file card's background tint) and the editor's
min height drops from three lines to two.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
The hover overlay and pointer cursor were gated on onAttachmentClick,
so surfaces without a handler showed no affordance at all. Chips are
now always interactive-looking, and the overlay drops from 10% to 4%
foreground.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
Six more commands (Review, Continue in new chat, Fast, Feedback, Init,
MCP) push the menu past its max height, exercising the scroll fade.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
Both packages' stories dropped their hand-written title prefixes; the
config now scopes each package's components directory so the sidebar
shows one flat, path-derived list.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7 issues found across 17 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts">

<violation number="1" location="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts:52">
P3: Audio-context shutdown failures are silently swallowed in both teardown paths, making cleanup failures invisible; logging a warning with context (or documenting an explicit best-effort rationale) would make resource problems diagnosable.

(Based on your team's feedback about surfacing swallowed async failures.)</violation>

<violation number="2" location="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts:102">
P1: Rapidly starting dictation before microphone permission resolves can leave an earlier microphone stream and recorder running because each call passes the `sessionRef.current` guard and the later session overwrites the ref; reserving an in-flight start (and cancelling it on unmount) would ensure only one session is owned and cleaned up.</violation>

<violation number="3" location="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts:103">
P2: Denying microphone access or having no input device produces an unhandled promise rejection because the composer invokes `start()` with `void` and this rejection is not caught; handling the failure in the hook or at the button boundary would keep normal permission failures observable without an unhandled rejection.

(Based on your team's feedback about handling async errors explicitly.)</violation>

<violation number="4" location="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts:133">
P2: Returning to a recording after a long background/throttled interval can freeze the UI: this loop performs one append per elapsed 60 ms and repeated shifts of the 4096-entry history in a single animation frame. Collapsing or capping missed intervals, or using a ring buffer, would bound the work before redrawing.</violation>

<violation number="5" location="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts:168">
P2: A failed transcription request becomes an unhandled rejection: `finish()` rethrows the provider error after resetting the status, while `ComposerBody` calls it with `void`; catching/reporting provider failures in this flow or at the caller would prevent the rejected promise from escaping.

(Based on your team's feedback about handling async errors explicitly.)</violation>
</file>

<file name="packages/chat-ui/src/components/LexicalComposer/components/ComposerBody/ComposerBody.tsx">

<violation number="1" location="packages/chat-ui/src/components/LexicalComposer/components/ComposerBody/ComposerBody.tsx:684">
P2: Pressing Enter can still submit and clear the draft while dictation is recording or transcribing, even though this branch disables Send; the later transcript is then inserted into the emptied editor. The keyboard submit path should apply the same dictation-status guard, or the editor should be disabled until dictation finishes.</violation>
</file>

<file name="packages/chat-ui/src/components/LexicalComposer/LexicalComposer.stories.tsx">

<violation number="1" location="packages/chat-ui/src/components/LexicalComposer/LexicalComposer.stories.tsx:692">
P3: stubMicrophone() permanently overrides navigator.mediaDevices.getUserMedia on the shared Storybook page and never closes its AudioContext. Because Storybook reuses one window across stories, once the Recording story plays the mock leaks into the rest of the session, and the oscillator graph keeps running for the page's lifetime.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

};

const start = async () => {
if (sessionRef.current) return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Rapidly starting dictation before microphone permission resolves can leave an earlier microphone stream and recorder running because each call passes the sessionRef.current guard and the later session overwrites the ref; reserving an in-flight start (and cancelling it on unmount) would ensure only one session is owned and cleaned up.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts, line 102:

<comment>Rapidly starting dictation before microphone permission resolves can leave an earlier microphone stream and recorder running because each call passes the `sessionRef.current` guard and the later session overwrites the ref; reserving an in-flight start (and cancelling it on unmount) would ensure only one session is owned and cleaned up.</comment>

<file context>
@@ -0,0 +1,176 @@
+	};
+
+	const start = async () => {
+		if (sessionRef.current) return;
+		const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+		const recorder = new MediaRecorder(stream);
</file context>

// gets the measured peak so gaps never read as sudden silence.
const peak = Math.max(SILENCE_FLOOR, bucketPeakRef.current);
let pushed = false;
while (now >= nextBarAtRef.current) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Returning to a recording after a long background/throttled interval can freeze the UI: this loop performs one append per elapsed 60 ms and repeated shifts of the 4096-entry history in a single animation frame. Collapsing or capping missed intervals, or using a ring buffer, would bound the work before redrawing.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts, line 133:

<comment>Returning to a recording after a long background/throttled interval can freeze the UI: this loop performs one append per elapsed 60 ms and repeated shifts of the 4096-entry history in a single animation frame. Collapsing or capping missed intervals, or using a ring buffer, would bound the work before redrawing.</comment>

<file context>
@@ -0,0 +1,176 @@
+			// gets the measured peak so gaps never read as sudden silence.
+			const peak = Math.max(SILENCE_FLOOR, bucketPeakRef.current);
+			let pushed = false;
+			while (now >= nextBarAtRef.current) {
+				historyRef.current.push(peak);
+				if (historyRef.current.length > 4096) historyRef.current.shift();
</file context>

<button
type="button"
aria-label="Send message"
disabled

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Pressing Enter can still submit and clear the draft while dictation is recording or transcribing, even though this branch disables Send; the later transcript is then inserted into the emptied editor. The keyboard submit path should apply the same dictation-status guard, or the editor should be disabled until dictation finishes.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/LexicalComposer/components/ComposerBody/ComposerBody.tsx, line 684:

<comment>Pressing Enter can still submit and clear the draft while dictation is recording or transcribing, even though this branch disables Send; the later transcript is then inserted into the emptied editor. The keyboard submit path should apply the same dictation-status guard, or the editor should be disabled until dictation finishes.</comment>

<file context>
@@ -629,32 +663,70 @@ export function ComposerBody({
+						<button
+							type="button"
+							aria-label="Send message"
+							disabled
+							className="flex size-8 shrink-0 cursor-not-allowed items-center justify-center rounded-lg bg-secondary text-muted-foreground"
+						>
</file context>

}

// Speech-like synthetic mic input so the story needs no permission prompt.
function stubMicrophone() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: stubMicrophone() permanently overrides navigator.mediaDevices.getUserMedia on the shared Storybook page and never closes its AudioContext. Because Storybook reuses one window across stories, once the Recording story plays the mock leaks into the rest of the session, and the oscillator graph keeps running for the page's lifetime.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/LexicalComposer/LexicalComposer.stories.tsx, line 692:

<comment>stubMicrophone() permanently overrides navigator.mediaDevices.getUserMedia on the shared Storybook page and never closes its AudioContext. Because Storybook reuses one window across stories, once the Recording story plays the mock leaks into the rest of the session, and the oscillator graph keeps running for the page's lifetime.</comment>

<file context>
@@ -605,70 +658,116 @@ function ChatScreen() {
 
-export const ChatScreenExample: Story = {
+// Speech-like synthetic mic input so the story needs no permission prompt.
+function stubMicrophone() {
+	const context = new AudioContext();
+	const oscillator = context.createOscillator();
</file context>

if (!session) return;
cancelAnimationFrame(session.frame);
for (const track of session.stream.getTracks()) track.stop();
session.audioContext.close().catch(() => {});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Audio-context shutdown failures are silently swallowed in both teardown paths, making cleanup failures invisible; logging a warning with context (or documenting an explicit best-effort rationale) would make resource problems diagnosable.

(Based on your team's feedback about surfacing swallowed async failures.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts, line 52:

<comment>Audio-context shutdown failures are silently swallowed in both teardown paths, making cleanup failures invisible; logging a warning with context (or documenting an explicit best-effort rationale) would make resource problems diagnosable.

(Based on your team's feedback about surfacing swallowed async failures.) </comment>

<file context>
@@ -0,0 +1,176 @@
+			if (!session) return;
+			cancelAnimationFrame(session.frame);
+			for (const track of session.stream.getTracks()) track.stop();
+			session.audioContext.close().catch(() => {});
+			sessionRef.current = null;
+		};
</file context>

ScrollToBottomButton wraps the message scroller's end button as a
floating circular control that fades out when the transcript is at
the bottom. Dictation failures are now classified: start errors
(permission denied, missing or busy microphone, unsupported device)
surface through a new dictation.onError callback for app-owned
toasts, while transcription failures keep the recorded audio and show
retry/discard controls in the composer row so a flaky request never
loses the user's speech.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
Auto-records against the synthesized mic, fails the transcription to
land on the error row, then restores the fake connection so clicking
retry inserts the transcript from the kept audio.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts">

<violation number="1" location="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts:157">
P2: A MediaRecorder construction failure leaves the newly acquired microphone stream active while UI returns to idle. Stop `stream` tracks in this catch before reporting the startup error.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment on lines +157 to +165
let stream: MediaStream;
let recorder: MediaRecorder;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
recorder = new MediaRecorder(stream);
} catch (cause) {
onError?.(describeStartError(cause));
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A MediaRecorder construction failure leaves the newly acquired microphone stream active while UI returns to idle. Stop stream tracks in this catch before reporting the startup error.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts, line 157:

<comment>A MediaRecorder construction failure leaves the newly acquired microphone stream active while UI returns to idle. Stop `stream` tracks in this catch before reporting the startup error.</comment>

<file context>
@@ -100,8 +152,17 @@ export function useDictation({
-		const recorder = new MediaRecorder(stream);
+		setError(null);
+		retryAudioRef.current = null;
+		let stream: MediaStream;
+		let recorder: MediaRecorder;
+		try {
</file context>
Suggested change
let stream: MediaStream;
let recorder: MediaRecorder;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
recorder = new MediaRecorder(stream);
} catch (cause) {
onError?.(describeStartError(cause));
return;
}
let stream: MediaStream | undefined;
let recorder: MediaRecorder;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
recorder = new MediaRecorder(stream);
} catch (cause) {
for (const track of stream?.getTracks() ?? []) track.stop();
onError?.(describeStartError(cause));
return;
}

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 6 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts">

<violation number="1" location="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts:159">
P2: A consumer/editor error is reported as a transcription failure and the recording is retained for retry because `onTranscript` is inside this catch. Limiting the catch to `transcribe(audio)` and invoking `onTranscript` after successful transcription avoids misleading errors and duplicate insertion retries.</violation>

<violation number="2" location="packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts:162">
P2: A recorder-construction failure leaves the microphone stream active because this new catch returns without stopping the tracks acquired by `getUserMedia`. Stopping the acquired stream before returning would prevent a live microphone indicator and leaked tracks on later start attempts.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

retryAudioRef.current = null;
let stream: MediaStream;
let recorder: MediaRecorder;
try {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A consumer/editor error is reported as a transcription failure and the recording is retained for retry because onTranscript is inside this catch. Limiting the catch to transcribe(audio) and invoking onTranscript after successful transcription avoids misleading errors and duplicate insertion retries.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts, line 159:

<comment>A consumer/editor error is reported as a transcription failure and the recording is retained for retry because `onTranscript` is inside this catch. Limiting the catch to `transcribe(audio)` and invoking `onTranscript` after successful transcription avoids misleading errors and duplicate insertion retries.</comment>

<file context>
@@ -100,8 +152,17 @@ export function useDictation({
+		retryAudioRef.current = null;
+		let stream: MediaStream;
+		let recorder: MediaRecorder;
+		try {
+			stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+			recorder = new MediaRecorder(stream);
</file context>

try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
recorder = new MediaRecorder(stream);
} catch (cause) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A recorder-construction failure leaves the microphone stream active because this new catch returns without stopping the tracks acquired by getUserMedia. Stopping the acquired stream before returning would prevent a live microphone indicator and leaked tracks on later start attempts.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/LexicalComposer/hooks/useDictation/useDictation.ts, line 162:

<comment>A recorder-construction failure leaves the microphone stream active because this new catch returns without stopping the tracks acquired by `getUserMedia`. Stopping the acquired stream before returning would prevent a live microphone indicator and leaked tracks on later start attempts.</comment>

<file context>
@@ -100,8 +152,17 @@ export function useDictation({
+		try {
+			stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+			recorder = new MediaRecorder(stream);
+		} catch (cause) {
+			onError?.(describeStartError(cause));
+			return;
</file context>

While recording or on a failed transcription, Escape cancels the
session outright — no transcription, audio discarded — taking
priority over every other Escape behavior, mirroring the reference
priority ladder where dictation abort sits above menu dismissal and
stop-turn. The discard button shares the same cancel path, and
opening dictation closes the browse menu.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
The editor library is an implementation detail and shouldn't name the
public component. PromptInput matches the AI-elements vocabulary; the
LexicalComposer*-prefixed types follow (PromptInputProps, commands,
attachments, dictation), and the CSS hooks become prompt-input-*.
Composer-domain types (ComposerChip, mention providers) and
ComposerDropZone keep their names.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
File cards categorize by mime type before falling back to extension
sets, adding audio and image icons, and video attachments render a
muted thumbnail in the preview slot like images do. Non-decodable
media still demotes to a file card through the existing error path.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
Deletes the unused formatBytes util and moves RemoveButton into its
own folder under AttachmentPills, which used it in both chip styles.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY
The rail story's Jump to latest pill predated the circular
scroll-to-bottom treatment; the demo now matches it.

Claude-Session: https://claude.ai/code/session_0114z2gU9LFJjbwSiyfLTkzY

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 36 files (changes from recent commits).

You’re at about 90% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/chat-ui/src/components/PromptInput/index.ts">

<violation number="1" location="packages/chat-ui/src/components/PromptInput/index.ts:11">
P2: Dictation consumers cannot import the public `PromptInputDictation` or `PromptInputDictationError` types from `@superset/chat-ui/PromptInput`, even though the component module exposes them and `PromptInputProps` uses the former. Re-export both types from this barrel so the documented dictation API is usable without reaching into internal files.</violation>
</file>

<file name="packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.tsx">

<violation number="1" location="packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.tsx:161">
P2: Video attachments now allocate object URLs that leak when the composer unmounts before submit or removal. A cleanup effect should revoke every remaining attachment preview URL on unmount, matching the existing remove/submit cleanup paths.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

PromptInput,
type PromptInputAttachment,
type PromptInputCommand,
type PromptInputProps,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Dictation consumers cannot import the public PromptInputDictation or PromptInputDictationError types from @superset/chat-ui/PromptInput, even though the component module exposes them and PromptInputProps uses the former. Re-export both types from this barrel so the documented dictation API is usable without reaching into internal files.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/PromptInput/index.ts, line 11:

<comment>Dictation consumers cannot import the public `PromptInputDictation` or `PromptInputDictationError` types from `@superset/chat-ui/PromptInput`, even though the component module exposes them and `PromptInputProps` uses the former. Re-export both types from this barrel so the documented dictation API is usable without reaching into internal files.</comment>

<file context>
@@ -5,9 +5,9 @@ export {
+	PromptInput,
+	type PromptInputAttachment,
+	type PromptInputCommand,
+	type PromptInputProps,
+	type PromptInputSubmitPayload,
+} from "./PromptInput";
</file context>
Suggested change
type PromptInputProps,
type PromptInputDictation,
type PromptInputDictationError,
type PromptInputProps,

id: crypto.randomUUID(),
file,
previewUrl:
file.type.startsWith("image/") || file.type.startsWith("video/")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Video attachments now allocate object URLs that leak when the composer unmounts before submit or removal. A cleanup effect should revoke every remaining attachment preview URL on unmount, matching the existing remove/submit cleanup paths.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.tsx, line 161:

<comment>Video attachments now allocate object URLs that leak when the composer unmounts before submit or removal. A cleanup effect should revoke every remaining attachment preview URL on unmount, matching the existing remove/submit cleanup paths.</comment>

<file context>
@@ -159,9 +157,10 @@ export function ComposerBody({
-					? URL.createObjectURL(file)
-					: undefined,
+				previewUrl:
+					file.type.startsWith("image/") || file.type.startsWith("video/")
+						? URL.createObjectURL(file)
+						: undefined,
</file context>

This branch was previously deployed

1 inactive deployment
preview — c348fb0d Deployed Aug 12, 2026 by saddlepaddle via Deploy Marketing #7496
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant